Tips
Alt-u: upper case word starting at cursor
Alt-l: lower case word starting at cursor
Ctrl-k: kill (ie, cut) all characters after cursor
Ctrl-u: kill all characters before cursor
Ctrl-y: paste last killed characters
Ctrl-f: move cursor forward by one character (same as right arrow)
Ctrl-b: move cursor backward by one character (same as left arrow)
Alt-f: move cursor forward by one word (same as Ctrl-right arrow)
Alt-b: move cursor backward by one word (same as Ctrl-left arrow)
https://mastodon.social/@YesIKnowIT/106757814475112522
General
basename: file name with extensiondirname: name of parent directory- Iterate over all directories in a directory:
for dir in */; do ... done - Bash functions (like unix processes) exit code must fall in the range [0.255]. That means no negative exit codes.
'Options'
-n: not set-z: is set ('is zero')-f: check if a file exists- Strings with
$-sign prefix
Special variables
$-: string with set of options in current shell$@: all positional arguments$#: number of positional arguments
Function args:
$1, $2, …
$0 is still script name
$USER: current username$HOME: home dir of current user
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
- Repeat last command:
!! - Repeat nth command from last in history:
!-<n>
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
-z: true if argument string is null-n: true if argument string is not null
References:
man bash- https://stackoverflow.com/questions/19074542/is-there-a-list-of-if-switches-anywhere
- https://stackoverflow.com/questions/18096670/what-does-z-mean-in-bash
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 ).
files=$(ls -1 workspace/)is not an arrayfiles=($(ls -1 workspace/))is an array
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
-f/-d: true if file/directory exists-s: true if file is non-empty (non-zero size)-r/-w/-x: true if file is readable / writable / executable- -
z: true if variable is unset or is empty string -e: any kind of file-S: Socket-L: Symbolic link-b: block special file-c: character special file
From: https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash
Check if a variable is set
- To check if variable is set, not whether it is empty.
- Note that
$is not uesd for variable name in the test.
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"
fiReplace -d with -f for files.
Pass contents of a file as an argument
In bash: "$(</path/to/file.txt)".
echo "$(</data/2.txt)"See:
- https://unix.stackexchange.com/questions/58212/how-do-i-pass-the-contents-of-a-file-as-a-command-line-parameter
- https://unix.stackexchange.com/questions/361309/how-to-pass-the-contents-of-a-file-to-an-option-parameter-of-a-function
- https://unix.stackexchange.com/questions/393351/pass-contents-of-file-as-argument-to-bash-script
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
- mktemp: temporary file
- mktemp -d: temporary directory
Check if a variable is set
-n: not set-z: is set ('is zero')
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
- mktemp: temporary file
- mktemp -d: temporary directory
Check if a variable is set
if [ -n $var ]; then
echo "var is set"
fi
if [ -z $var ]; then
echo "var is not set"
fiFind 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
- VARNAME reference should be ${VARNAME}
- VARNAME can be $VARNAME
Info
cdis same ascd $HOME- Tips for logging in bash scripts: link
Show bash version info
C-x C-v
Sample output:
GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)