Skip to content

Instantly share code, notes, and snippets.

@bretonics
Last active November 4, 2020 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bretonics/4476778f9086c77ccac5 to your computer and use it in GitHub Desktop.
Save bretonics/4476778f9086c77ccac5 to your computer and use it in GitHub Desktop.
Tricks to remember on the CL
Script source path - ${BASH_SOURCE} contains full bath to script
# /path/to/repo/bin/script
BIN_PATH="$(dirname ${BASH_SOURCE})"  # gets 'bin' directory path script is in
DIR_PATH="$(dirname $BIN_PATH)"       # gets the main 'repo' directory path
Rename file by replacing old text pattern with new (overwrite existing)
for f in *.txt ; do echo "${f/old/new}"; done

for f in *.txt; do mv "$f" `echo $f | sed s/old/new/\`; done
Find symlink to same inode
find -L / -samefile path/to/file.txt
Loop through results of find
find | while read directory; do $directory; done
Find modified n*24 hours ago and remove
n="+15"
find /home/directory/*/dir/* -type d -mtime ${n} -prune -exec rm -rfv "{}" \;
Read in password
read -p "Password: " pswd
echo "User pswd was $pswd"
Array Expansion
${list[@]}
Variable prefix/suffix (extension) removal
${0#*.}
${0%.*}
Variable substring
## syntax ##
${parameter:offset:length}

${a:1}    # everything after position 1
${a:0:5}  # offset 0 with length 5

## syntax ##
${parameter:-default}  # set a default if $parameter udefined

${a:-$b}  # output: ${a} ? ${a} : ${b}
Substring Replacement
# Parameter expansion with substring replacement
# It takes the existing variable username in `=${username` then will replace every occurrence `//` of `*= ` with `/...` (nothing).
# NOTE: the closing '/' is implied
username=${username//*= /}
Substring Removal
# Deletes shortest match of $substring from FRONT of $string.
${string#substring}

# Deletes longest match of $substring from FRONT of $string.
${string##substring}

# Deletes shortest match of $substring from BACK of $string.
${string%substring}

# Deletes longest match of $substring from BACK of $string.
${string%%substring}

# Find and remove (replace with nothing) 'chars followed by any number of zeroes'.
echo "$TEST" | sed 's/chars0*//'
Only print the actual match (not the entire matching line), use a substitution.
# Replace whatever comes before and after the match with nothing, then print the whole line (p)
sed -n 's/.*\([0-9][0-9]*G[0-9][0-9]*\).*/\1/p'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment