`inpath`

Coding along with the book Wicked Cool Shell Scripts- 101 Scripts for Linux, OS X, and UNIX Systems.

This is the script from Page 11:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/bash

in_path()
{
cmd=$1
ourpath=$2
result=1
oldIFS=$IFS
IFS=":"

for directory in $ourpath; do

# If i double quoted `$ourpath`, it will not word split, and the loop will only run once.

if [ -x "$directory/$cmd" ]; then
result=0
fi
done

IFS=$oldIFS
return $result
}

checkForCmdInPath()
{
var=$1

if [ ! "$var" = "" ]; then
if [ "${var:0:1}" = "/" ]; then
# Checks whether the command represented by the `$var` is an absolute path or not.
if [ ! -x "$var" ]; then
return 1
fi
elif ! in_path "$var" "$PATH"; then
return 2
fi
fi
}

Positional parameters

See here

A Quick Word

It is good practice to put double quotes around variables in Bash because it prevents word splitting and globbing.

  • Word splitting is the process of breaking up a string into separate words based on whitespace. If a variable contains spaces, without quotes, Bash will treat each space-separated word as a separate argument. This can cause unexpected behavior if the variable is used as an argument to a command.

  • Globbing is the process of expanding wildcard characters such as * and ? into a list of matching filenames. If a variable contains a glob character, without quotes, Bash will try to expand it into a list of matching filenames. This can also cause unexpected behavior if the variable is used as an argument to a command.

By putting double quotes around variables, Bash treats the variable as a single argument, preserving any whitespace or glob characters within the variable. This helps to ensure that the variable is interpreted correctly and the script behaves as expected.

Special variables

$IFS

The internal field separator (IFS) is a special variable in Bash that specifies the delimiter used to separate fields in a string. By default, the IFS is set to whitespace (i.e., space, tab, and newline characters).

`$?

Display the return values of functions.

1
echo $?

You can use it immediately after calling a function with return value.

Slice

[ "${var:0:1}" = "/" ];

The slicing starts at index 0 and lasts for the duration of a single character.

Compare

String comparison

= tests if two strings are equal. For example, if [ "$string1" = "$string2" ] would be true if $string1 and $string2 have the same value.

Pattern matching

== tests if a string matches a pattern using globbing, which is a way to match filenames based on wildcard characters. For example, if [[ "$string" == a* ]] would be true if $string starts with the letter “a”.