Bash


Tips

https://mastodon.social/@YesIKnowIT/106757814475112522

General

'Options'

Special variables

Function args:

References:

Get directory of a file path

$(dirname /path/to/a/file.txt)  # /path/to/a/

Handy for use with cd command to do stuff like

cd $(dirname $_)  # go to directory of last argument of last command

'Unexport' a variable

Use -n option of export without the $ in the variable.

export -n <variable>

History

Alias

Set alias

alias <name>='<command>'

Like

alias emacs='emacs -nw'

Unset alias

unalias <name>

Easy renaming :-)

mv path/to/file/{a,b}.ext

is same as

mv path/to/file/a.ext path/to/file/b.ext

Skip history for a command

Add a space before the command.

Bash: loop

for i in {1..10}; do echo $i; done

String concatenation

Reference: https://www.delftstack.com/howto/linux/how-to-concatenate-strings-using-bash/

Two string variables

a="hi"
b="hello"
c=$a$b
echo $c  # hihello

A string variable and a string literal

a="hi"
c="${a}hello"
echo $c  # hihello

A string variable and a number

a="hi"
b=10
c=$a$b
echo $c  # hi10

Dot operator

a="hello";
echo "hi".${a}  # hihello

+= operator

a="hi"
b="hello"
a+=$b  # hihello

Dot in beginning of a line

. in bash is same as the source command.

As in

. ~/bash_aliases

Reference: https://unix.stackexchange.com/questions/114300/whats-the-meaning-of-a-dot-before-a-command-in-shell

Pass argument to function

Use $1 for first argument, $2 to 2nd, and so on.

Tricks

Repeat previous command with a change

Use ^old^new to replace occurrence of the string old with new (they needn't be strings themselves).

fam@ubu:~$ echo hello
hello
fam@ubu:~$ ^l^hehe
echo hehehelo
hehehelo

https://mastodon.social/@YesIKnowIT/107537702786292217

Bash if switches

References:

Arrays

https://stackoverflow.com/questions/1335815/how-to-slice-an-array-in-bash

# Creation
$ arr=(foo bar 1 1.2)

$ echo $arr
foo

$ echo ${arr[@]}
foo bar 1 1.2

# Indexing
$ echo ${arr[1]}
bar

# Slicing
$ echo ${arr[@]:1:2}
bar 1

# Slice from pos 1 to end of array
$ echo ${arr[@]:1}
bar 1 1.2

$ echo ${arr[@]::2}
foo bar

Note that array needs the ( and ).

hex arithmetic in bash

$ echo $((0x12))
18

$ echo $((0x12 << 2))
72

octal arithmetic in bash

$ echo $((8#13))
11

$ echo $((8#13 << 2))
44

Bash: Edit and execute last n commands

# last one command
fc

# last 3 commands
fc -3 0

This will open up an editor ($FCEDIT is looked at first to select the editor) with the last n commands (default n=1). We can edit them as we like. When the editor is closed, those commands will be executed.

See history with timestamps

# For like "2022-07-04 05:16:19"
HISTTIMEFORMAT="%F %T "
history

Use the variable in .bashrc to make this permanent.

Reference: https://askubuntu.com/questions/391082/how-to-see-time-stamps-in-bash-history

Options

set -e Stop script on error
set -u Throw error on unset variable use
set -o pipefail Throw error if any command in a 'pipe-chain' of
commands fail even if other commands succeeded

Tests

From: https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash

Check if a variable is set

a=2 
if [[ -v a ]; then
  echo "a set"
else
  echo "a not set"
fi

Check if a directory/file exists

if [[ -d /home/user ]; then
  echo "/home/user exists"
else
  echo "/home/user doesn't exist"
fi

# Or

if [[ ! -d /home/user ]; then
  echo "/home/user doesn't exist"
else
  echo "/home/user exists"
fi

Replace -d with -f for files.

Pass contents of a file as an argument

In bash: "$(</path/to/file.txt)".

echo  "$(</data/2.txt)"

See:

Show definition of a bash function

Use type.

For example, I got a function named csv:

$ type csv
csv is a function
csv ()
{
    if [ $# -lt 1 ]; then
        echo "Please specify file name";
    else
        if [ -f $1 ]; then
            column -s, -t < $1 | less -#2 -N -S;
        else
            echo "$1: File not found";
        fi;
    fi
}

heredoc

cat << SAMEWORD
hello
world
SAMEWORD

Reference: https://tldp.org/LDP/abs/html/here-docs.html

Temporary files

Check if a variable is set

if [ -n $var ]; then
  echo "var is set"
fi

if [ -z $var ]; then
  echo "var is not set"
fi

Reference: https://tldp.org/LDP/abs/html/here-docs.html

Temporary files

Check if a variable is set

if [ -n $var ]; then
  echo "var is set"
fi

if [ -z $var ]; then
  echo "var is not set"
fi

Find key code of keyboard keys

In a terminal do: C-v <key>.

Eg:

^[[A Up arrow
^[[D Left arrow
^[[5~ Page up
^[[1;5D Ctrl-Left

The ^[ is an escape sequence or something. The remaining characters are the real deal.

These codes might be dependent on the terminal being used.

https://stackoverflow.com/questions/11816046/signs-for-the-enter-key-page-up-and-page-down

Returning values from function

return is for stating exit code? Values are 'returned' via printing. Do an echo.

Underscore in variable name

Info

Show bash version info

C-x C-v

Sample output:

GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)