Bash cheat sheet: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
No edit summary |
||
Line 70: | Line 70: | ||
==Cool code sample of functions call using args and return codes== | |||
#!/bin/bash | #!/bin/bash | ||
main() { | main() { | ||
Line 79: | Line 79: | ||
myreturnvalue=$? | myreturnvalue=$? | ||
#echo "myreturnvalue is "$myreturnvalue | #echo "myreturnvalue is "$myreturnvalue | ||
if [ $myreturnvalue == "1" ] ; then | if [ $myreturnvalue == "1" ] ; then | ||
echo "EXIST" | echo "EXIST" | ||
else | else | ||
Line 86: | Line 86: | ||
} | } | ||
function chkFile(){ | function chkFile(){ | ||
if [ -f $1 ]; then #Check | if [ -f $1 ]; then #Check if file exists | ||
return 1 | return 1 | ||
else | else |
Revision as of 23:07, 5 November 2021
- Getoptions with flags
while getopts "f" option; do case ${option} in f) flag="1" *) echo "unknown parameter" exit;; esac done
- Getoptions with args
while getopts "a:" option; do case ${option} in a) arg="${OPTARG}" *) echo "unknown parameter" exit;; esac done
- Condition -OR-
if "$isA" || "$isB"; then do-something fi
- Condition if var is defined
if [ ${var+x} ]; then do-something fi
- Print Text
cat << EOF Any ... text ... EOF }
- Read tokenized configuration file
. /etc/os-release echo $VERSION_ID
- Search in file, return bool
if grep -q search-arg "/etc/file.conf"; then do-something fi
- Search and replace
sed -i -r 's/(.*)umask 022(.*)$/\t#Changed\n\tumask 027/gi' /etc/profile
- CRLF within string
scriptmsg+="Hello\n" scriptmsg+="World\n" echo -e $scriptmsg
NL=$'\n' echo -e " Hello${NL}Wolrd"
echo " Hello World "
Cool code sample of functions call using args and return codes
#!/bin/bash main() { declare test_path='/etc' declare test_file='motd' chkFile "${test_path}/${test_file}" myreturnvalue=$? #echo "myreturnvalue is "$myreturnvalue if [ $myreturnvalue == "1" ] ; then echo "EXIST" else echo "NO EXIST" fi } function chkFile(){ if [ -f $1 ]; then #Check if file exists return 1 else return 0 fi } main "$@"; exit 0