Bash

Table of Contents

1. Shell movements

 Shell movements
 ===============

Cursor position represented by []
---------------------------------

 ctrl-a <-----------------> ctrl-e  | moving
  alt-b    <-------->        alt-f  |
 ctrl-b       <-->          ctrl-f  |

      $ mv file[].txt dir/

 ctrl-w    <-------->       alt-d   | erasing
 ctrl-u <-----------------> ctrl-k  |

2. Interactive Shells

3. Bash Startup Files

3.1. Prevent autostart for programs when inside an Emacs shell

To avoid running programs that may not render well within an Emacs shell when loading ~/.bashrc etc

if [[ -z $INSIDE_EMACS ]]
then
    # Things to do when not using a shell inside Emacs
fi

4. Shell Parameter Expansion (/#, ##, %% etc)

4.1. Return the same value from 2 different strings

youtube_link_channel="https://yewtu.be/feed/channel/foo"
# OR
youtube_link_channel="https://www.youtube.com/feeds/videos.xml?channel_id=foo"

# both youtube_link_channel return "foo"
youtube_channel_id="${youtube_link_channel##*[=/]}"

5. Redirections (>, >>, <, 2>&1 etc)

6. List function names and bindings

bind -p

7. Bind a function named water to M-s f

bind -x '"\esf":water'

8. Display all locations containing an executable

type -a foo

9. Print the commands as they are executed

++ in the output mean forking/subshell

set -x
<commands>
bash -x <file>

10. Check for unset variables

bash -u <file>

11. Pipe status exit codes

false | true | false | false
echo "${PIPESTATUS[*]}"

12. Date using strftime(3)

Print the date using builtin printf and strftime(3).

local date
printf -v date '%(%Y-%m-%d)T'
echo -n "$date"

13. Array of files basename

fn() {
    local files=(/path/to/files/file*)
    files=("${files[@]##*/}")

    declare -p files
}

14. Unset values in array

# Iterate over the green blocklists
for green_blocklist in "${green_blocklists[@]}"
do
    # Remove green blocklists from the blue blocklists array
    for index in "${!blue_blocklists[@]}"
    do
        if [[ ${blue_blocklists[index]} == "$green_blocklist" ]]
        then
            unset 'blue_blocklists[index]'
            blue_blocklists=("${blue_blocklists[@]}")
        fi
    done
done

15. One liners

15.1. Find dotfiles packages not managed by Ansible

while read -r pkg; do if grep -rq "$pkg" ~/projects/ansible-dotfiles; then echo "pkg found: $pkg"; else echo "pkg not found: $pkg"; fi done < ~/.dotfiles/.pkg*

15.2. Flatpak remove all document ids for exported files

while read -r id; do flatpak document-unexport --doc-id "$id" && echo "done $id"; done < <(flatpak documents)

16. References