Shell Scripting - Hoi-Jeon/Wiki GitHub Wiki
Change the picture format
for i in *.jpg; do convert $i ${i%jpg}png; done
Export?
$ MYVAR=1729
$ export MYVAR=1729
The first definition creates a variable named MYVAR and assigns it the value 1729. This is a shell variable. The second definition with the export command is another way of defining a variable. It creates a variable named MYVAR, assigns it the value 1729, and marks it for export to all child processes created from that shell. This is an environment variable. Defining a Bash Variable With or Without ‘export’
When to use () vs. {} in bash?
Parentheses() cause the commands to be run in a subshell. Braces{} cause the commands to be grouped together but not in a subshell. When to use () vs. {} in bash? How to use double or single brackets, parentheses, curly braces
Manipulating Strings
String Length
${#string}
stringZ=abcABC123ABCabc
echo ${#stringZ} # 15
Substring Extraction
${string:position} Extracts substring from $string at $position. ${string:position:length} Extracts $length characters of substring from $string at $position.
stringZ=abcABC123ABCabc
# 0123456789.....
# 0-based indexing.
echo ${stringZ:0} # abcABC123ABCabc
echo ${stringZ:1} # bcABC123ABCabc
echo ${stringZ:7:3} # 23A
Delete string
${string%substring} Deletes shortest match of $substring from front of $string. ${string%%substring} Deletes longest match of $substring from front of $string.
# Make the volume of all mp3 files (having a space in the file name" by 12dB
#!/bin/bash
for f in *.mp3; do
echo "$f" ....converting
sox "$f" "${f%.mp3}"_12dB.mp3 gain -n -12
done
extBefore="JPG"
extAfter="PNG"
for f in *.${extBefore}; do
mv -- $f "${f%.${extBefore}}.${extAfter}"
done
Substring Replacement
${string/substring/replacement} Replace first match of $substring with $replacement. ${string//substring/replacement} Replace all matches of $substring with $replacement.
stringZ=abcABC123ABCabc
echo ${stringZ/abc/xyz} # xyzABC123ABCabc
# Replaces first match of 'abc' with 'xyz'.
echo ${stringZ//abc/xyz} # xyzABC123ABCxyz
# Replaces all matches of 'abc' with # 'xyz'.
Caret(^) in shell script
Beginning of line ( ^ ) caret Symbol ^ matches the expression at the start of a line.
$ grep "^Nov 10" messages.1
Nov 10 01:12:55 gs123 ntpd[2241]: time reset +0.177479 s
Nov 10 01:17:17 gs123 ntpd[2241]: synchronized to LOCAL(0), stratum 10
Nov 10 01:18:49 gs123 ntpd[2241]: synchronized to 15.1.13.13, stratum 3
Exception in the character class If you want to search for all the characters except those in the square bracket, then use ^ (Caret) symbol as the first character after open square bracket. The following example searches for a line which does not start with the vowel letter from dictionary word file in linux. Here, the brackets means the characters in the bracket will be found individually.
grep -i "^[^aeiou]" /usr/share/dict/linux.words