bash condition test if - ghdrako/doc_snipets GitHub Wiki
Condition
- && and operator
- || or operator
# succeed with the cd or bail with a message
cd $DIR || { echo "cd to $DIR failed." ; exit ; }
# the && and || operators are of equal precedence and are left Associated
[ -n "$DIR" ] && [ -d "$DIR" ] && cd "$DIR" || exit 2
test
Istnieją dwie wersje test. Jedna jako polecenie wbudowane w powloke i drugie jako samodzielny program. Domyślnie pierwszeństwo mają polecenia wbudowane. Aby wywołać wersję samodzielna trzeba podać ścieżkę.
Polecenie test zawsze zwraca true lub false czyli odpowiednio 0 lub 1. Bez argumentów test zwraca false.
Podstawowa skladnia
test wyrazenie
Aby odwrócić dzialanie
test ! wyrazenie
Połączenie wielu wyrażenie za pomocą opcji -a i -o odpowiednio and i or.
test wyr1 -a wyr2
test wyr1 -o wyr2
Skrócona forma polecenia test to nawiasy kwadratowe
test ! wyrażenie
[! wyrażenie]
test -f /etc/hosts -a -r /etc/hosts
[ -f /etc/hosts -a -r /etc/hosts ]
[ -f /etc/hosts -a -r /etc/hosts ] && Cat /etc/hosts
IF structure
[
is a Bash builtin, while [[
is a Bash keyword
[...]
if [ $Name != $USER ]
then
echo "Your name isn't your username"
else
echo "Your name is your username"
fi
# True if the value of $Name is not equal to the current user's login username
# NOTE: if $Name is empty, bash sees the above condition as:
if [ != $USER ]
# which is invalid syntax
# so the "safe" way to use potentially empty variables in bash is:
if [ "$Name" != $USER ] ...
# which, when $Name is empty, is seen by bash as:
if [ "" != $USER ] ...
# which works as expected
# There is also conditional execution
echo "Always executed" || echo "Only executed if first command fails"
# => Always executed
echo "Always executed" && echo "Only executed if first command does NOT fail"
# => Always executed
# => Only executed if first command does NOT fail
# To use && and || with if statements, you need multiple pairs of square brackets:
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
then
echo "This will run if $Name is Steve AND $Age is 15."
fi
if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
then
echo "This will run if $Name is Daniya OR Zach."
fi
[ ... ](/ghdrako/doc_snipets/wiki/-...-)
Nie są kompatybilne z Bourn Shell.
[ ... ](/ghdrako/doc_snipets/wiki/-...-)
is more robust than [ ... ]
because it handles special characters
and logical operators more gracefully. It avoids issues like word
splitting and allows for advanced features such as regex-style pattern
matching (==, !=). Unlike [ ... ], it does not require special quoting for variables containing spaces.
Jako słowo kluczowe [[ pasuje swoje argumenty zanim powłoka je rozwinie stąd też każdy ponedynczy parametr będzie reprezentowany jako pojedynczy argument.
echo "zawartość pliku" >"moj plik"
FILE="moj plik"
[ -f $FILE && -r $FILE ](/ghdrako/doc_snipets/wiki/--f-$FILE-&&--r-$FILE-) && Cat "$FILE"
[ -f "$FILE" -a -r "$FILE" ] && Cat "$FILE"
Nie musimy otaczać zmiennych cudzysłowiem ale jest to dobra praktyka. Dodatkowo [[ obsługuje && więc nie trzeba używać -a.
[ ... ](/ghdrako/doc_snipets/wiki/-...-)
is specific to Bash and not available in all shells. In POSIX-
compliant scripts, [ ... ]
should be used.Inside [ ... ](/ghdrako/doc_snipets/wiki/-...-)
, pattern matching
works without needing * to be quoted, whereas [ ... ]
requires careful quoting to avoid globbing and expansion.
Dopasowanie wzorca
[ $FILE = *.pl ](/ghdrako/doc_snipets/wiki/-$FILE-=-*.pl-) && cp "$FILE" /scripts
Wyrażenia regularne
To samo o powyzej
[ $FILE =~ \.pl$ ](/ghdrako/doc_snipets/wiki/-$FILE-=~-\.pl$-) && cp "$FILE" /scripts
Kropka ma znaczenie w wyrażeniu regularnym została poprzedzone \ aby je dezaktywowac
# There is also the `=~` operator, which tests a string against a Regex pattern:
[email protected]
if [ "$Email" =~ [a-z]+@[a-z]{2,}\.(com](/ghdrako/doc_snipets/wiki/net|org)-)
then
echo "Valid email!"
fi
# Note that =~ only works within double [ ](/ghdrako/doc_snipets/wiki/-) square brackets,
# which are subtly different from single [ ].
# See http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
shopt -s nocasematch # wyłączenie rozróżnianie wielkości liter w wrażeniach regularnych
shopt -u nocasematch # wlaczenie
# Numeric Conditions
[ NUM -eq NUM ](/ghdrako/doc_snipets/wiki/-NUM--eq-NUM-) Equal
[ NUM -ne NUM ](/ghdrako/doc_snipets/wiki/-NUM--ne-NUM-) Not equal
[ NUM -lt NUM ](/ghdrako/doc_snipets/wiki/-NUM--lt-NUM-) Less than
[ NUM -le NUM ](/ghdrako/doc_snipets/wiki/-NUM--le-NUM-) Less than or equal to
[ NUM -gt NUM ](/ghdrako/doc_snipets/wiki/-NUM--gt-NUM-) [ NUM -ge NUM ](/ghdrako/doc_snipets/wiki/-NUM--ge-NUM-) Greater than or equal to
# String Conditions
[ STRING == STRING ](/ghdrako/doc_snipets/wiki/-STRING-==-STRING-) # Equal
[ STRING != STRING ](/ghdrako/doc_snipets/wiki/-STRING-!=-STRING-) # Not Equal
[ -z STRING ](/ghdrako/doc_snipets/wiki/--z-STRING-) # Empty string
[ -n STRING ](/ghdrako/doc_snipets/wiki/--n-STRING-) # Not empty string
[ STRING =~ STRING ](/ghdrako/doc_snipets/wiki/-STRING-=~-STRING-) # Regular expression match
# check string pattern matching
input="hello123"
if [ $input == hello* ](/ghdrako/doc_snipets/wiki/-$input-==-hello*-); then
echo "The input starts with 'hello'"
else
echo "The input does not start with 'hello'"
fi
number=10
if [ $number -gt 5 && $number -lt 20 ](/ghdrako/doc_snipets/wiki/-$number--gt-5-&&-$number--lt-20-); then
echo "The number is between 5 and 20"
fi
# Is the length of the variable zero? i.e., empty or null
if [ -z "$VAR" ](/ghdrako/doc_snipets/wiki/--z-"$VAR"-); then
echo empty
fi
# This checks for a nonzero length, i.e., not empty, not null
if [ -n "$VAR" ](/ghdrako/doc_snipets/wiki/--n-"$VAR"-); then
echo "VAR has a value:" $VAR
fi
# Same here
if [ "$VAR" ](/ghdrako/doc_snipets/wiki/-"$VAR"-); then
echo even easier this way
fi
#File Conditions
[ -f FILE ](/ghdrako/doc_snipets/wiki/--f-FILE-) # Is a file
[ -d FILE ](/ghdrako/doc_snipets/wiki/--d-FILE-) # Is a directory
[ -e FILE ](/ghdrako/doc_snipets/wiki/--e-FILE-) # Exists
[ -r -w -x FILE ](/ghdrako/doc_snipets/wiki/--r--w--x-FILE-) # Is readable, Writable, executable
[ -h FILE ](/ghdrako/doc_snipets/wiki/--h-FILE-) # Is symbolic link
#File Conditions Example
if [ ! -f ./pdfgen/pdfgen ]; then
echo "Building pdfgen binary"
npm run --prefix pdfgen build:linux
else
echo "Pdfgen binary already exists, skipping build"
fi
if [ ! -L /usr/local/bin/heroku ];
then
wget https://cli-assets.heroku.com/branches/stable/heroku-linux-amd64.tar.gz
sudo mkdir -p /usr/local/lib /usr/local/bin
sudo tar -xvzf heroku-linux-amd64.tar.gz -C /usr/local/lib
sudo ln -s /usr/local/lib/heroku/bin/heroku /usr/local/bin/heroku
fi
# Boolean conditions:
a|[ ! EXPR ](/ghdrako/doc_snipets/wiki/-!-EXPR-) |Not
a|[ BOOL && BOOL ](/ghdrako/doc_snipets/wiki/-BOOL-&&-BOOL-) |And
a|[ BOOL ](/ghdrako/doc_snipets/wiki/|-BOOL-) |OR
the double bracket syntax supports an additional comparison operator, =~, which allows the use of regular expressions.
if [ $FN =~ .*xyzz*.*jpg ](/ghdrako/doc_snipets/wiki/-$FN-=~-.*xyzz*.*jpg-); then ...
Check if an environment variable is set in bash
# long
if [ -z "${CIRCLE_BRANCH}" ](/ghdrako/doc_snipets/wiki/--z-"${CIRCLE_BRANCH}"-); then
npm run redis-cli flushall
fi
npm run sync
# one-liner
[-z "${CIRCLE_BRANCH}"] && npm run redis-cli flushall; npm run sync
Przypisanie wartości domyslnej
name=$1
[ -z $name ] && name="Anonymous"
prosciej
name={$1-"Anonymous"}