Bash

Bash is a Unix shell. This section covers many useful bash commands.

Chmod

• Reference

To copy the permissions from one file to another use:

chmod --reference=<source file to copy permissions from> <target file>

Cron

Cron is used to execute scheduled commands

Df

View file system disk space usage.

$ df -h
  • -h: Human readable, in powers of 1024

Du

Estimate file space usage (can be used on directories, because directories are files too 😉)

$ du -h video.mp4
  • -h: Human readable

Find

View file system disk space usage.

$ find ./ -name "*.html"

Really Useful:

  • -name "<name>": Name of file. -iname can be used to ignore case
  • -type <type>: f for file. d for directory
  • ! <flag>: Find the opposite
  • -exec <Command> {} \;: Execute command using found files. Example:
    $ find ./ type f -name "main.html" -exec rm {} \;
  • -size <size>: Find files greater than <size>. Suffix with "k" for kilobytes, "M" for megabytes, or "G" for gigabytes. To find less than use <-size>.
  • -delete: Delete found matches

Somewhat Useful:

  • -L: Follow symbolic links
  • -perm <777>: Find files with permissions
  • -user <User>: Find file based on owned user
  • -mtime <hour>: Files last modified in <hours>. -mmin <-min> is the minute version
  • -atime <hour>: Files last accessed in <hours>. -amin <-min> is the minute version
  • -maxdepth <depth>: Max depth of search

Io Redirection

• Append

To append to stream, use >>

• File Discriptor

The following maps the file redirect to File descriptor:

File File Descriptor
STDIN 0
STDOUT 1
STDERR 2

• Join

To join two streams you can do thing 2>&1. This will join stderr into stdout.

• Pipe

To pipe output from one program to another, use: |.

• Redirect

  • <: Redirect stdin
  • >: Redirect stdout
  • 2>: Redirect stderr

Keyboard Shortcuts

Handy-dandy command line shortcuts!

• Cursor

Move the cursor around when typing commands.

  • Ctrl + a: Go to the beginning of the line
  • Ctrl + e: Go to the end the of the line
  • Alt + b: Go back one word
  • Alt + f: Go forward one word
  • Ctrl + xx: Move between the beginning of the line and the current position of the cursor

• Cut Paste

  • Ctrl + w: Cut the word before the cursor
  • Ctrl + u: Cut the line before the cursor
  • Ctrl + k: Cut the line after the cursor
  • Ctrl + y: Paste (yank) from the terminal's clipboard
  • Alt + .: Recall the last arguments of the previous command

• Deleting Text

Delete part of a line of text.

  • Alt + d: Delete all characters after the cursor until the next whitespace

• Fixing Typos

  • Alt + t: Swap the current word with the previous word

• History

Command history can be gone through via the ↑↓. In the middle of your history? Use Ctrl + c to get back to the start!

Here are some commands to further explore your bash history:

  • Alt + r: Revert command pulled from history to its original form (undo changes to command)
  • Ctrl + r: Recall (search) for the last instance of a command
    • Enter: Run the searched command
    • Ctrl + g: Leave the search without running a command

• Processes

Manage running processes

  • Ctrl + c: Kill the current running process
  • Ctrl + z: Suspends the current running process and moves it to the background
    • Use bg to start the process in the background
    • Use jobs and fg %<Number> to bring it back to the foreground
  • Ctrl + d: Send the EOF (End-Of-File) marker. If in bash, the terminal will exit

• Screen

Control the screen

  • Ctrl + l: Clear the screen
  • Ctrl + s: Stop all output to the screen (nice when there is LOTS of output and you want to look at something now)
    • Ctrl + q: Resume output to the screen

Ln

ln - Link files. Make a file that links to another file/directory.

There are two types of links, hard link and symbolic link.

  • Hard Link: Similar to a shared pointer in C++. A hark link creates another file with a link to the underlying inode of the target file. If the target file is deleted, you can still access the data via the link. Cannot be used on directories or on other disk partitions.
  • Symbolic Link: Similar to a pointer in C++. A symbolic link is just another name for the file. It's essentially just a shortcut to the file. Can be used on directories. Probably the more used out of the two.
$ ln -s /path/to/file /path/to/symlink
  • -s: Make a symbolic link. Without this flag, a hard link is created
  • -f: Update a symlink. Overwrites the previous symlink path.
  • --backup: Creates a backup of a file. Will have a ~ near the end of the name

Ls

$ ls

Flags, ordered by personal usefulness

  • -l: List directory contents, one element per line
  • -a: List all of the directory contents, including those starting with '.' (hidden files)
  • -h: Print human readable data sizes
  • Sorting Order:
    • -r: Reverse sorting order
    • -t: Sort by time, newest first
    • -S: Sort by file size, largest first
    • -X: Sort by extensions
  • -R: List subdirectories recursively (tree is prettier)
  • -U: Don't sort. Makes listing lots of files a lot faster

Nmcli

nmcli is a command-line tool for controlling the NetworkManager.

Arguments:

  • -a, --ask: Interact. Fill in missing arguments.
  • $ nmcli dev wifi list
    $ nmcli dev wifi connect "Name Of Network" -a

    Use readlink -f <file> to print the full path of a file.

    Recode

    recode allows you to convert a text file from one encoding to another, for example, ascii to html. This can be useful when you want to convert code that is full of templates (i.e. <>) to html. Example:

    cat main.cpp | recode ascii..html | xclip

    Rsync

    rsync is remote sync. It can be used to sync files between hosts. It's great for transferring files to/from another host.

    Example:

    $ rsync -rltvPh /source/path drc@127.0.0.1:/target/path

    Args:

    • -r: Recursive
    • -l: Copy symlinks as symlinks
    • -t: Preserve modification times
    • -v: Print lots of stuff
    • -P: Progress bar per file
    • -h: Human readable
    • -n: Dry run. Good for seeing what will be transferred/updated
    • --delete: Delete extraneous files from destination directories, i.e. remove files from destination that are not in source

    Scripting

    Programming language commands for bash. Files with the .sh extension are bash scripts.

    • For Loop

    One liner:

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

    Multiple Lines:

    for i in {1..9}
    do
        echo ${i}
    done

    Different ranges:

    • Numeric Range:
      for i in {1..9}; do echo ${i}; done
    • For Each:
      for i in apple banana cherry; do echo ${i}; done
    • Command:
      for i in $(<Command>); do echo ${i}; done
    • Array:
      ARR=('apple' 'banana' 'cherry')
      for i in "${ARR[@]}"; do echo ${i}; done

    Break and continue work as expected.

    • While Loop

    Works in the same fashion as a for-loop, however, the loop continues until the control expression is false.

    For example, this command prints every line in a file:

    while read line;
    do
        echo "$line"
    done < file.txt

    Slurm

    Slurm is used for cluster management and job scheduling. Slurm has three key features:

    1. Allocates resources to users
    2. Provides a framework for starting, executing, and monitoring work
    3. Manages a queue of pending work

    • Sbatch

    Submit a bash script to slurm. Slurm will schedule this bash script given the arguments presented in the script.

    $ sbatch script.sh

    Script example:

    #! /bin/bash
    #################### Batch Headers ####################
    #SBATCH -p drcluster        # Get it? DRC cluster ;)
    #SBATCH -J hello_world      # Custom name
    #SBATCH -o results-%j.out   # stdout/stderr redirected to file
    #SBATCH -N 3                # Number of nodes
    #SBATCH -n 1                # Number of cores (tasks) 
    #######################################################
    
    python hello_world.py
    

    Arguments:

    • -N --nodes: Number of nodes (machines) to allocate.
    • -n --ntasks: Number of cores to be allocated. Cores may or may not come from the same machine. Defaults to one task per node.
    • --ntasks-per-node: Specify the number of tasks per node to use. --ntasks takes precedence.
    • -p --partition: Specify partition to run on.
    • --mem: Amount of memory to reserve (G for gigabytes)
    • -J: Job name (for sacct or squeue)
    • -o: Output file name (%j is job number)
    • --nodelist: Request specific nodes. Comma separated node list or a filename (should have '/' in the name)

    Environment variables:

    • $SLURM_SUBMIT_DIR: The directory you submitted the job from. Might want to cd to here at the start of the script. Should be a place where all of the nodes can access (shares storage).

    • Scancel

    scancel is used to cancel a task

    $ scancel <jobID>

    • Scontrol

    scontrol allows you to view or alter a job's details

    View job details:

    $ scontrol show job 14

    Suspend a job:

    $ sudo scontrol suspend 14

    Continue a job:

    $ scontrol resume 14

    Give up on a job:

    $ scontrol release 14

    • Sinfo

    sinfo provides information about the cluster

    $ sinfo
    PARTITION  AVAIL  TIMELIMIT  NODES  STATE NODELIST
    drcluster*    up   infinite      3   idle node[02-04]
    
    • PARTITION is the cluster partition name
    • TIMELIMIT is the maximum amount of time a user can request resources for this partition
    • NODES is the number of compute nodes (clients) on this partition
    • STATE
      • MIXED: Some CPUs are ALLOCATED (used) while others are IDLE
      • RESERVED: Noe is reserved in advanced

    • Squeue

    squeue displays all submitted jobs.

    $ squeue
    JOBID PARTITION     NAME     USER ST       TIME  NODES NODELIST(REASON)
       22 drcluster hostname    drc14 PD       0:00      3 (PartitionConfig)
    

    A list of state codes can be found HERE.

    • Srun

    srun allows you to run parallel jobs directly from the command line. See sbatch for command line arguments.

    $ srun --nodes=3 hostname
    node03
    node02
    node04
    

    To run an interactive srun session:

    $ srun --pty /bin/bash
    

    Sshfs

    sshfs (Secure SHell FileSystem) allows you to mount a filesystem via ssh onto your local machine.

    Example:

    $ sshfs user@example.org: ~/local/dir

    Tar

    Archiving command. Can be used with gzip to make a tar ball (.tar.gz).

    • Compress

    $ tar -czvf compress.tar.gz /path/to/compress
    • -c: Create a new archive (group files together, the .tar part)
    • -z: Filter archive through gzip (compress, the .gz part)
    • -v: Verbose, list files processed (can get annoying)
    • -f: Name to save archive as

    Remove files while being archived:

    tar -czf compressed.tar.gz --remove-files path/to/compress

    • Uncompress

    $ tar -xzvf compress.tar.gz
    • -x: Extract files from an archive (Undoes the .tar part)
    • -z: Filter archive through gzip (uncompress, the .gz part)
    • -v: Verbose, list files processed (can get annoying)
    • -f: Name of archive file to use

    Tmux

    Terminal Multiplexer. Used to open a lot of sessions in a single window. Can create tabs and split a window into multiple parts. Tmux sessions stay active even after closing a connection (ssh), so it is a handy way to keep your work or have running process run in the background when you're not connected to the host.

    My personal ".tmux.conf" file can be found HERE. My plugin install script can be found HERE.

    • Commands

    To enter command mode: Ctrl + b, :

    • Copy Mode

    • Ctrl + b, [: Enter copy mode
    • Use vim navigation keys or arrow keys to move around
    • Space: Start selecting
    • Esc: Clear selection
    • Enter: Copy selection
    • Ctrl + b, ]: Paste

    • Panes

    • Alt + ← ↑ → ↓: Switch to pane
    • Ctrl + b, v: Split plane vertically
    • Ctrl + b, s: Split plane horizontally
    • Ctrl + b, {: Move the current pane left
    • Ctrl + b, }: Move the current pane right
    • Ctrl + b, Space: Toggle between pane layouts
    • Ctrl + b, z: Pane zoom
    • Ctrl + b, !: Convert pane into a window
    • Ctrl + b + ← ↑ → ↓: Resize pane. Hold down the first to keys and tap the arrow key
    • Ctrl + b, x: Close current pane

    • Plugins

    Tmux plugin manager: TPM

    • Ctrl + b, Ctrl + I: Install plugins
    • Ctrl + b, Ctrl + U: Update plugins

    Tmux Resurrect: Restore tmux environment after system restart.

    • Ctrl + b, Ctrl + s: Save
    • Ctrl + b, Ctrl + r: Restore
    • Saved sessions are stored in ~/.tmux/resurrect/. With continuum the tmux environment is saved every 15 minutes. Every once in a while, saved sessions need to be purged.
    • To restore a previously saved session as the current session: ln -sf <desired resurrect> last. Will need to restore restore the session afterwards.

    • Sessions

    • Start a new session:
      $ tmux
    • Kill a session:
      $ tmux kill-session -t <session name >
    • Rename a session: Ctrl + b, $
    • Detach (leave) from session: Ctrl + b, d
    • List sessions:
      $ tmux ls
    • Enter an existing session:
      $ tmux a -t <session name>
    • Ctrl + b, r: Reload .tmux.conf file

    • Windows

    • Shift + ← →: Switch to window
    • Ctrl + b, c: Create a new window
    • Ctrl + b, ,: Rename window
    • Ctrl + b, &: Close current window
    • Ctrl + b, 0 ... 9: Select a window by number
    • Ctrl + b, : :swap-window -s <source window number > -t <target window number>: Create a new window

    Tree

    List contents of directories in a beautiful tree-like format

    $ tree
    • -d: Directories only
    • -l: Follow symbolic links
    • -L <level>: Max number of levels
    • --prune: Ignore empty directoires

    Xargs

    xargs allows you to transform inputs from one command and run them with another command.

    By default xargs takes input, separates it by blanks, and executes a command for each argument. Example:

    echo 'one two three' | xargs mkdir  # This will make three directories

    Useful arguments:

    • -d: Change the delimiter to something other than space, i.e. xargs -d "\n"
    • -p: Display each command and prompt the user to execute it

    Xclip

    • Clipboard

    To use xclip to copy to the clipboard for Ctrl + v functionality use:

    xclip -selection c

    It is recommended to make an alias for this in your bashrc profile.

    Xrandr

    Used to adjust the screen (resolution, size, orientation, etc.)

    • Multiple Monitors

    $ xrandr
    $ xrandr --auto --output <Screen> --mode <Resolution, ex 1440x1080>