What are these bash_profile functions doing? - shell

I'm confused about this conditional:
if [[ ! -z "$1" ]]
What is this language?
Here is what I'm familiar with for my terminal and bash_profile:
Bash is the shell, or command language interpreter, for the GNU
operating system.
and
Simply put, the shell is a program that takes your commands from the
keyboard and gives them to the operating system to perform. In the old
days, it was the only user interface available on a Unix computer.
Nowadays, we have graphical user interfaces (GUIs) in addition to
command line interfaces (CLIs) such as the shell.
On most Linux systems a program called bash (which stands for Bourne
Again SHell, an enhanced version of the original Bourne shell program,
sh, written by Steve Bourne) acts as the shell program.
function parse_git_branch {
branch=`git rev-parse --abbrev-ref HEAD 2>/dev/null`
if [ "HEAD" = "$branch" ]; then
echo "(no branch)"
else
echo "$branch"
fi
}
function prompt_segment {
# for colours: http://en.wikipedia.org/wiki/ANSI_escape_code#Colors
# change the 37 to change the foreground
# change the 45 to change the background
if [[ ! -z "$1" ]]; then
echo "\[\033[${2:-37};45m\]${1}\[\033[0m\]"
fi
}
function build_mah_prompt {
# time
ps1="$(prompt_segment " \# ")"
# cwd
ps1="${ps1} $(prompt_segment " \w ")"
# git branch
git_branch=`parse_git_branch`
if [[ ! -z "$git_branch" ]]
then
ps1="${ps1} $(prompt_segment " $git_branch " 32)"
fi
# next line
ps1="${ps1}\n\$ "
# set prompt output
PS1="$ps1"
}
PROMPT_COMMAND='build_mah_prompt'

The language is Bash, a modern shell based on the old Bourne shell and
(mostly) compatible with POSIX standards.
test aka [
[[ is a Bash extension of the test command also known as [. The test command is a separate executable but since it’s so useful for shell programming, most (if not all) modern shells implement it as a shell builtin. The following commands show that both versions are available on many systems:
$ type -a test
test is a shell builtin
test is /usr/bin/test
$ type -a [
[ is a shell builtin
[ is /usr/bin/[
For more info, see man test or help test (with Bash).
[[
[[ is implemented as a Bash keyword (not an external command). It originally came from the Korn shell and works similarly but has many improvements over the original [ command. See the following for more info:
What is the difference between test, [ and [[ ?
What's the difference between [ and [[ in bash?
Is [[ ]] preferable over [ ] in bash scripts?
Specific example
According to man test (POSIX specification)
−z string True if the length of string string is zero; otherwise, false.
Thus, the [[ -z "$1" ]] construct returns 0 (value for True in Unix shells) if $1, the first positional parameter to a script or function is an empty string. Introducing the negation ! operator converts the expression to its Boolean opposite, i.e, False if the following expression evaluates to True and vice versa.
To sum up, the whole expression evaluates to True if the first argument to the function is a non-empty string and False if it’s empty (or possibly not set at all).
If you read the above links, you’ll notice that [[ ! -z "$1" ]] is actually equivalent to [[ -n "$1" ]] which return True if $1contains anything, i.e., is not empty. This can be further shortened to [[ $1 ]] as quotes aren’t required for variables within [[.
Note: the portable version (for POSIX shells) is [ -n "$1" ] or [ "$1" ] (where the variables have to be quoted to protect from pathname expansion, word splitting and other potential side effects). See http://mywiki.wooledge.org/Quotes for more info.
Functions
The remaining code are shell functions which look like they’re used to build up a colourful prompt which provides details of the status of a git repository if the current working directory is under version control.

Related

Bash to zsh actual syntax differences, such as brackets in 'if' [duplicate]

The zsh_test.sh is simple, as following:
#!/usr/bin/env zsh
if [ $USER == 'root' ]; then
echo "root"
else
echo "not root"
fi
Copy and paste the above codes into a zsh shell, it executed well.
$ #!/usr/bin/env zsh
$ if [ $USER == 'root' ]; then
then> echo "root"
then> else
else> echo "not root"
else> fi
not root
But directly execute script file zsh_test.sh, got an error.
$ ./zsh_test.sh
./zsh_test.sh:3: = not found
I now see what's wrong: You are the victim of a fairly obscure zsh mechanism, which is described in the zshexpn man page and is called '=' expansion. From the man-page:
If a word begins with an unquoted `=' and the EQUALS option is set, the remainder of the word is taken as the name of a command. If a command exists by that name, the word is replaced by the full pathname of the command.
You can try it with the command
echo ==
which also outputs this error message. For instance, on my platofm
echo =ruby
outputs /usr/bin/ruby, because this is where I have ruby installed. If you would have in your PATH a program named =, the == would resolve to this path.
While it is unusual to use a double == sign inside [ ... ], the zsh implementation of this command allows it, but you would have to quote the operator, to avoid =-expansion:
if [ $USER '==' root ]; then
An alternative would be to use [[ ... ]] instead. This is not a command, but a syntactic construct, and expansion rules are different inside it. Therefore
if [[ $USER == root ]]; then
would work as well.
I'm afraid that you are using test command wrong. Let's see why.
test command is defined since Unix version III. You can often find this command also as [ binary in your PATH. In most modern shells (let's pretend that bash is modern shell as well), there is also implementation of test or [ as builtin command. From the specification, the only valid way to compare two strings is this:
STRING1 = STRING2
the strings are equal
STRING1 != STRING2
the strings are not equal
Original strict POSIX implementation of test command is somehow limited and can be difficult to use. But it is portable, and that it's main strength. But what if you don't care about portability at all? Then there are Conditional Expressions.
Conditional Expressions, available as [[ builtin command, are improved, not POSIX compatible replacement for original test command. Look in the manual for the things you can compare with them to get the idea. Double equality sign (==) is also supported (and the documentation explicitly says it's for compatibility with other sorts of computer language.)
Conclusion?
When you are writing scripts for particular shell, like zsh, and you are absolutely sure that portability is not important for you, always use [[ instead of [. Your life will be easier and change to your script is minimal:
#!/usr/bin/env zsh
if [[ $USER == 'root' ]]; then
echo "root"
else
echo "not root"
fi
If portability between different shells and environments is necessary, you will have to use original test or [ command, and forget about zsh, == and many other things at all.
#!/bin/sh
if [ "$USER" = 'root' ]; then
printf '%s\n' "root"
else
printf '%s\n' "not root"
fi

Why the zsh codes like [ $var == 'str' ] runs well as a command but error as a script file?

The zsh_test.sh is simple, as following:
#!/usr/bin/env zsh
if [ $USER == 'root' ]; then
echo "root"
else
echo "not root"
fi
Copy and paste the above codes into a zsh shell, it executed well.
$ #!/usr/bin/env zsh
$ if [ $USER == 'root' ]; then
then> echo "root"
then> else
else> echo "not root"
else> fi
not root
But directly execute script file zsh_test.sh, got an error.
$ ./zsh_test.sh
./zsh_test.sh:3: = not found
I now see what's wrong: You are the victim of a fairly obscure zsh mechanism, which is described in the zshexpn man page and is called '=' expansion. From the man-page:
If a word begins with an unquoted `=' and the EQUALS option is set, the remainder of the word is taken as the name of a command. If a command exists by that name, the word is replaced by the full pathname of the command.
You can try it with the command
echo ==
which also outputs this error message. For instance, on my platofm
echo =ruby
outputs /usr/bin/ruby, because this is where I have ruby installed. If you would have in your PATH a program named =, the == would resolve to this path.
While it is unusual to use a double == sign inside [ ... ], the zsh implementation of this command allows it, but you would have to quote the operator, to avoid =-expansion:
if [ $USER '==' root ]; then
An alternative would be to use [[ ... ]] instead. This is not a command, but a syntactic construct, and expansion rules are different inside it. Therefore
if [[ $USER == root ]]; then
would work as well.
I'm afraid that you are using test command wrong. Let's see why.
test command is defined since Unix version III. You can often find this command also as [ binary in your PATH. In most modern shells (let's pretend that bash is modern shell as well), there is also implementation of test or [ as builtin command. From the specification, the only valid way to compare two strings is this:
STRING1 = STRING2
the strings are equal
STRING1 != STRING2
the strings are not equal
Original strict POSIX implementation of test command is somehow limited and can be difficult to use. But it is portable, and that it's main strength. But what if you don't care about portability at all? Then there are Conditional Expressions.
Conditional Expressions, available as [[ builtin command, are improved, not POSIX compatible replacement for original test command. Look in the manual for the things you can compare with them to get the idea. Double equality sign (==) is also supported (and the documentation explicitly says it's for compatibility with other sorts of computer language.)
Conclusion?
When you are writing scripts for particular shell, like zsh, and you are absolutely sure that portability is not important for you, always use [[ instead of [. Your life will be easier and change to your script is minimal:
#!/usr/bin/env zsh
if [[ $USER == 'root' ]]; then
echo "root"
else
echo "not root"
fi
If portability between different shells and environments is necessary, you will have to use original test or [ command, and forget about zsh, == and many other things at all.
#!/bin/sh
if [ "$USER" = 'root' ]; then
printf '%s\n' "root"
else
printf '%s\n' "not root"
fi

different result for [[ ]] and [] string comparator "<"

I was doing some tests, and I couldn't understand why there two results are different. The first one seems correct, since in a crescent ordenation, the character 'f' comes first than 'F'
$ [[ "Foo" < "foo" ]]
$ echo $?
1
So why this one is incorrect?
$ [ "Foo" \< "foo" ]
$ echo $?
0
Both [[ and [ are built into bash. [ is equivalent to the test command, also a builtin. (Well, almost equivalent; [ requires a matching ], test doesn't.)
According to the bash manual:
When used with test or [, the < and > operators sort
lexicographically using ASCII ordering.
(Bourne shell builtins are documented here).
But the expression in [[ ... ]] follows the rules of Bash conditional expressions:
When used with [[, the < and > operators sort
lexicographically using the current locale. The test command uses
ASCII ordering.
(There's another test / [ command provided as part of the GNU coreutils package, typically /usr/bin/test. This command doesn't provide < and > operators, which are not specified by POSIX. The external command should be irrelevant if you're using bash, unless you explicitly give the full path /usr/bin/test.)
Your question is tagged both "bash" and "sh". If you're using bash, you should probably use the bash-specific [[ feature rather than [. If you want greater portability (e.g., if your script might be used with a shell other than bash), you can't rely on the [[ builtin, and you can't assume that [ or test supports < and >.
The BSD test implementation of <[1], like the bash-builtin one, is not character-collation-order aware; it refers only to "the binary value" of the characters in question.
The bash [[ ]] implementation of < is characterset-aware: It honors the current language/locale's selected collation order.
If you set LC_COLLATE=C (specifying ASCII sort order), then [[ ]] will do the same:
$ (export LC_COLLATE=C; [[ "Foo" < "foo" ]]; echo $?)
0
[1] - > is not a POSIX-standardized test operator, so all answers must be in the context of a specific implementation.

logical OR existence test for shell variables under bash

I need to perform some logic based on if shell_var_1 OR shell_var_2 is set under bash.
If I use #!/bin/sh, I could just use:
if [ "$shell_var_1" -ne "0" -o "$shell_var_2" -ne "0" ] ; then
logic
fi
This just uses "-o" from test (http://unixhelp.ed.ac.uk/CGI/man-cgi?test)
However, if I specify #!/bin/bash, and want to use the '-v' option to test the shell variable's existence (added from bash 4.2 onwards), how'd I go about doing the same?
Ref: https://tiswww.case.edu/php/chet/bash/bash.html
if [ -v shell_var_1 -o -v shell_var_2 ] ; then
logic
fi
^ Is this considered correct? Am I not mixing bash and the test operator?
[[ $shell_var_1 || $shell_var_2 ]]
...is a very succinct and idiomatic way to write this in bash, compatible back to ancient releases, assuming that you consider a variable set to an empty value not to exist.
If you want a portable alternative which treats variables set to zero-byte values as unset, then
[ -n "$shell_var_1" ] || [ -n "$shell_var_2" ]
...will serve.
If you want a portable alternative that treats variables set to empty values as existing, then
[ -n "${shell_var_1+set}" ] || [ -n "${shell_var_2+set}" ]
...will do this.
If you really want to use -v (thus, treating variables set to empty values as existing, but being needlessly incompatible with POSIX shells and older bash releases -- including those shipped with MacOS), then use [[ ]] -- which makes it unmistakably clear to readers that you're using bash-only syntax, and isn't prone to some obscure bugs which test or [ (even the bash built-in form of them) are prone to when used in more than 2-arg form:
[[ -v shell_var_1 || -v shell_var_2 ]]

How to set a toggle on linux (True or False) bash command?

I currently assigned my thinkvantage button to turn off tap to click on my trackpad, but I'd like to convert it to a toggle on/off switch.
For the moment, this is the bash command I use to turn it off (or on with CTRL):
gsettings set org.gnome.settings-daemon.peripherals.touchpad tap-to-click true
gsettings set org.gnome.settings-daemon.peripherals.touchpad tap-to-click false
In other words, ho do I turn this into a conditional toggle switch bash statement?
Presumably something like this:
#!/bin/bash
class=org.gnome.settings-daemon.peripherals.touchpad
name=tap-to-click
status=$(gsettings get "$class" "$name")
status=${status,,} # normalize to lower case; this is a modern bash extension
if [[ $status = true ]]; then
new_status=false
else
new_status=true
fi
gsettings set "$class" "$name" "$new_status"
Breaking it down into pieces:
#!/bin/bash ensures that the interpreter for this script is bash, enabling extended syntax such as [[ ]].
The syntax $( ) is "command substitution"; this runs a command, and substitutes the output of that command. Thus, if the output is true, then status=$(...) becomes status=true.
The parameter expansion ${name,,} expands the contents of name while converting those contents to all-lowercase, and is only available in newer versions of bash. If you want to support /bin/sh or older releases of bash, consider status=$(printf '%s\n' "$status" | tr '[:upper:]' '[:lower:]') instead, or just remove this line if the output of gsettings get is always lowercase anyhow.
The comparison [[ $status = true ]] relies on the bash extension [[ ]] (also available in other modern ksh-derived shells) to avoid the need for quoting. If you wanted it to work with #!/bin/sh, you'd use [ "$status" = true ] instead. (Note that == is allowable inside [[ ]], but is not allowable inside of [ ] on pure POSIX shells; this is why it's best not to be in the habit of using it).
Note that whitespace is important in bash! foo = bar, foo= bar and foo=bar are completely different statements, and all three of them do different things from the other two. Be sure to be cognizant of the differences in copying from this example.
Toggling seconds on the Ubuntu Unity clock (directly pastable as a command for a keybinding):
bash -c 'gsettings set com.canonical.indicator.datetime show-seconds $(gsettings get com.canonical.indicator.datetime show-seconds | perl -neprint/true/?false:true)'
For GNOME:
bash -c 'gsettings set org.gnome.desktop.interface clock-show-seconds $(gsettings get org.gnome.desktop.interface clock-show-seconds | perl -neprint/true/?false:true)'
Source: https://www.commandlinefu.com/commands/view/24256/toggle-the-touchpad-on-or-off
synclient TouchpadOff=$(synclient -l | grep -q 'TouchpadOff.*1'; echo $?)
or
tp=$(synclient -l | grep TouchpadOff | awk '{ print $3 }') && tp=$((tp==0)) && synclient TouchpadOff=$tp

Resources