Bash references and shortcuts

Restricted BASH shell

Starting BASH with -r or running rbash will start a restricted bash shell. In this you cannot:-

  • cd to change directory
  • Set or reset the $PATH or $SHELL
  • use absolute paths for commands (/path/to/command)
  • import envoronment functions
  • $SHELLOPTS not allowed
  • redirecting output (no > » | <> >& )
  • use exec

Don't rely on rbash for security on it's own, your login env needs to be set up correctly too.

Command Line arguments

Use these with:- $bash [options] [arguments]

 -c cmd  run cmd found from path search \\
 -D print double quotes strings to STDOUT \\
 -i run interactive mode
 -r run rbash ([[linux:bashshortcut#restricted_bash_shell|Bash references and shortcuts]])
 -s read in commands from STDIN - default mode
 --help show help info and quit
 --login behave as a login shell
 --noediting  don't use readline lib
 --noprofile don't use any init files
 --norc don't use ~/.bashrc
 --posix follow POSIX standard
 --rcfile - use this file not the usual ~/.bashrc
 --restricted same as -r for rbash ([[linux:bashshortcut#restricted_bash_shell|Bash references and shortcuts]])
 --verbose  sets ''set -v'' for verbose
 --version shown version to STDOUT

Starting BASH

  1. Interactive - runs /etc/profile, ~/.bashprofile and ~/.bash_login. Logout, if present runs ~/.bash_logout
  2. Non interactive. Command substitution is from $BASH_ENV
  3. Interactive sh login - runs /etc/profile and ~/.profile. Skipped if invoked with –noprofile
  4. POSIX is started with –posix switch

Prompts

$ export PS1=">$ "

Primary prompt:- $PS1
Secondary prompt:- $PS2

\a  ASCII BEL Oct 07
\d  date WMD format
\e  ASCII escape sequence
\h  hostname to first '.'
\H  full hostname
\l  name of shell term device, eg ttyUSB0
\n  newline
\r  carriage return
\s  shell name
\t  time - 24hr HH:MM:SS
\T  time - 12hr HH:MM:SS
\u  username
\v  bash version
\V  bash version and patch level
\w  working directory
\W  base name of PWD
\!  history number of command
\#  command number
\$  a # for UID=0 (root) or a $ for regular user
\@  time in AM PM format
\\  backslash
\nnn Octal nnn character
\[  Start seq of non printing characters
\]  end seq of non printing characters

Default PS1 id \s-\v\$

$ export "PS1=\u@\H $> "
sysadmin@sysmgmt $>

BASH Defined variables

Variable Value
$n or $(n) Argument positional variables
$@ All positional variables
$# Number of supplied parameters
$? last return code
$$ Process number of current shell
$BASH file and path used to invoke BASH
$BASH_ENV Path of startup file
$BASH_VERSION / [0], [1], [2] etc Version of BASH and [0] is major and minor versions
$HOME Used for ~ expansion
$HOSTNAME Current host
$IFS Imput File Seperator
$PATH Search path for commands
$PS1 Primary prompt - \s-\v\$
$PS2 Secondary prompt - > or #
$PS3 Command prompt string #?
$PS4 tracimg prompt (+)
$PWD Current directory
$OLDPWD Previous directory
$SHELL Current Shell

Variable Substitution

$name             name variable
${name}           braces delimit name
${name=word}      Set name to word
${name?word}      use name if set otherwise use word
${name+word}      use word if name is set
${name[x]}        use xth element in array name
${#name}          length of variable name
${#name[*]}       number of elements in name array
${name#pattern}   remove shortest leading substringfrom name which matches pattern
${name##pattern}  remove longest leading substringfrom name which matches pattern
${name%pattern}   remove shortest trailing substringfrom name which matches pattern
${name%%pattern}  remove longest trailing substringfrom name which matches pattern

${name/patt/string} replace value of name with first match of patt
FIXME - Every match

Command Substitution

This allows a command to be run in a subshell from within a script, the original format used backticks (`) to surround the command, the current way is to use $(command):-

lsoutput=`ls -1`
 
lsoutput=$(ls -1)

Bash Array

myarrayname=("Tom" "Dick" "Harry")
 
numberarray(100 200 300 400)

Accessing an array - array elements start at 0!

${ArrayName[subscript]}
 
echo "${myarrayname[2]}"  # Harry
 
Number of elements:-
 
echo ${#myarrayname[@]} # 3
#!/bin/bash
city=("London" "Paris" "Berlin")
 
## number of elements in "$city" array
len=${#city[@]}
 
## Use bash for loop 
for (( i=0; i<$len; i++ )); do echo "${city[$i]}" ; done

$ ./city.sh
London
Paris
Berlin

$

Aliases

Alises allow a long and frequently used command to be 'aliases' by a briefer one.

Lifted from a Ubuntu .bashrc:-

aliases.txt
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

Arithmetic evaluations for expressions

Based on 'C' syntax, these use long integers. typeset -i will use just integers.

Evaluation is with several differnt syntax, the let built in, ((....)) and $((.....))

operator explanation
+, - Unary add and subtract
!, ~ Negation, locgical and bitwise
*, /, % multiplication, division and modulus
** exponentiation
<, ⇐, >, ⇒ greater than, less then or equals comparisons
=, != equals and not equals
& bitwise AND
| bitwise OR
&& logical AND with short circuit
|| logical OR with short circuit

Conditional Expressions

Tested with [[...]].

expression evaluation
string true if string is not NULL
-n string true if string has a non-zero length
-z string true if string has zero length
string == pattern true if string equals pattern
string != pattern true if string Not equals pattern
-b file true if file is a Block Device
-c file true if file is a Character Device
-d file true if file is a directory
-e file true if file exists
-f file true if file is a regular file
-h file true if file is a symbolic link
-O file true if owner is current UID
-r file true if file is readable
-w file true if file is writable
-x file true if file is executable
file1 -nt file2 true if file1 is newer than file2
file1 -ot file2 true if file1 is older than file2
file1 -ef file2 true if file1 is the same as file2
expr1 -eq expr2 true if expr1 equals expr2
expr1 -ne expr2 true if expr1 not equal to expr2
expr1 -lt expr2 true if expr1 less than expr2
expr1 -gt expr2 true if expr1 greater than expr2
expr1 -le expr2 true if expr1 less than or equal to expr2
expr1 -ge expr2 true if expr1 greater than or equal to expr2
(expr) true if expr is true
!expr true if expr is false
expr1 && expr2 true if expr1 AND expr2 are true
expr1 || expr2 true if expr1 OR expr2 are true

This page has been accessed:-
Today: 1
Yesterday: 0
Until now: 136

 
linux/bashshortcut.txt · Last modified: 29/12/2023 17:38 by andrew