Skip to main content



Access arguments from within a function

  • All: "@"
  • All starting after x: "${@:x}"
  • Positional: $1, $2, $x
  • Make argument list start after the first one: call shift or shift n to begin after the nth.

Define function

function hello () {
echo "Hello world"

Get file count in target directory

Including dotfiles

ls -1A | wc -l

Excluding dotfiles

ls -1 | wc -l
  • For directories other than the current one the path can be passed to the ls command.

Get full path of target file or dir

readlink -f filename

Iterate over a range of numbers including both limits

for i in "$(seq 1 3)"; do echo "$i"; done


Pause current job.


Restart last job.


Merge files in dir with cat and glob

Merges all files in the current dir into a single file.

cat * >> bigfile.txt
# Use *.extension instead of * to merge only files with the given extension.

Return to previous position in history after searching with Ctrl+r

Ctrl+c - End of history.

Ctrl+g - Last position before starting search.

Run command during logout

Add command to ~/.bash_logout.

Run executable file

Mark the file as executable.

chmod +x filename

Execute the file in the terminal with one of the following commands.

bash filename
  • The second option works even if the file doesn't have execution permission.

Send string or command output to stdin of another command

# Using pipes.
echo 'testOutput' | cut -c 5-
# With here-docs (strings only).
# Single-line string.
cat <<< 'test str'
# Multi-line string and command options.
cat <<EOF -n -s
line 2
# Using process substitution.
# < is for redirection to stdin, <() is the process substitution syntax.
cat < <(echo 'result sent to stdin')

Set environment variables

For all users

Add a line to /etc/profile.

export VARNAME=value

Or create a file with .sh extension containing it in /etc/profile.d.

For a given user

Add line to ~/.bash_profile or ~/.bashrc.

  • These statements are executed after user log in.

Use parts of last command in current one

$ echo a
$ echo !:1

$ echo a b
a b
$ echo !:2

$ echo c d
c d
$ echo !:2 q !:1
d q c

$ rm somefile
$ echo !:0