bash IFS

Updated: 07 March 2024

Explode a string about a comma character, using the Internal Field Separator variable

mystr=foo,bar,spam

IFS=',' read -ra frags <<< $mystr
for frag in "${frags[@]}"; do
  echo "$frag"
done

# output
foo
bar
spam

bash history

Updated: 15 April 2023

History doesn’t get written to .bash_history until log off.

Show history

history

Clear session history

history -c

Delete item 234 from history

history -d 234

Writes all current session command history to the HISTFILE

history -w

Search history

Ctrl+R and start typing the previous command. Once a result appears, repeat Ctrl+R to see other matches. Enter to run command.

To re-run a command from history

!<item number>

bash process substitution

Updated: 11 January 2023

>(command_list)
<(command_list)

Process substitution feeds the output of a process (or processes) into the stdin of another process. It uses /dev/fd/<n> files to send the results of the process(es) within parentheses to another process. Effectively, process substitution turns a command into a temporary file, which is removed when the command completes.

cat <(echo hello world) # hello world
echo <(echo hello world) # /dev/fd/63

The first command converts the output of echo hello world into a file with contents hello world. The second command shows us the temp file in use.

The diff command requires files as arguments. So, comparing the contents of two directories can be achieved with diff and process substitution

diff <(ls /bin) <(ls /usr/bin)

bash sort

Updated: 04 March 2024

Sort by second column of tabulated data

$ printf "101\tc\n102\tb\n103\ta\n"
101	c
102	b
103	a

$ printf "101\tc\n102\tb\n103\ta\n" | sort -k2
103	a
102	b
101	c

bash expand

Updated: 01 January 2023

shell-expand-line

Check if shell-expand-line is bound to any keys

$ bind -P | grep shell-expand-line

If not add this to .inputrc

"\e\C-e": shell-expand-line

Test it

$ $HOME # Ctr+Alt+e, should print full path.

bash quoting

Updated: 31 December 2022

Single quotes

Single quoting is strong quoting, it preserves the literal value of each character

chris@ctd:~$ echo 'My home dir is $HOME'
My home dir is $HOME

bash loops

Updated: 31 December 2022

until loop

Very similar to the while loop, except that the loop executes until the test-command executes successfully. As long as this command fails, the loop continues.

until test-command; do
    consequent-commands;
done

bash exit code

Updated: 12 February 2023

#!/bin/bash -xv

# run date command
date

# exit code is in $?
status=$?

[ $status -eq 0 ] && echo "success" || echo "failure"