bash script

Bash: How to test file encoding and convert

Within a bash script, how to test the encoding of a file and convert the encoding if necessary?

Bash: adding inline comments within long/multiline command

One can break long commands like this:

cat "$1" | tr '\n' '\t' | sed  's/\t\t/\n/g' | sed 's/[0-9]*\t//1' | sed 's/^[^\t]*\t//' | sed 's/\t-/\n-/' | sed 's/\t/ /g' | sed 's/  / /g' | sed 's/^-//' | sed 's/^ *//' | sed 's/<[ib]>//' |  sed 's/<\/[ib]>//'

into multiple lines, using the backslash at the last character of each line:


cat "$1" \
| tr '\n' '\t' \
| sed 's/\t\t/\n/g'\
| sed 's/[0-9]*\t//1'\
| sed 's/^[^\t]*\t//'\
| sed 's/\t-/\n-/'\
| sed 's/\t/ /g'\
| sed 's/ / /g'\
| sed 's/^-//'\
| sed 's/^ *//'\
| sed 's/<[ib]>//'\

Bash: validating variables and parameters

Help us complete this page with more examples of validation.

Variables

The simplest validation is as follows:

if [[ "$variable" ]]; then
        echo "set"   
else
        echo "unset"
fi

It checks if a variable is set.

Beware, if you want to validate the value of the variable, you'll have to be more explicit:


variable=0
if [[ $variable ]]; then
echo "This gets printed because the variable is set."
elif [[ $variable == 1 ]]; then
echo "This does not get printed because the variable equals 0."
fi

Bash: how to test whether a variable is set?

Bash: how to test whether a variable is set?

For example, in a bash script, ${1} stands for the first argument the script was called with. However, ${1} might not be set.
How to test this?

sed: can't read : No such file or directory

Error message:

sed: can't read : No such file or directory

This is due to running sed with the option --in-place without having a given file:

$ sed --in-place s/from/to/ ""

In a bash script

This error is usually encountered when sed is employed within a bash script. For example:

#!/bin/bash
sed --in-place "s/from/to/" "${1}"

and forgetting to run the script with a file argument:
$ myscript.sh
sed: can't read : No such file or directory
$ myscript.sh file.txt # OK.

Syndicate content