Quoll Faq Bash

Faq bash

Posted on Posted in Faq

Rename a group of files based on a regex

Suppose you want to rename the name of a group of files that have the following template:

file1_tmp.sh
file2_tmp.sh
...
file99_tmp.sh

and suppose you want to remove the ‘_tmp’ middle part in all the files. We can use the command “rename” or “prename”:

 rename 's/_tmp//' *.sh

 

Redirect the standard error to the standard output

To redirect the standard error of a shell command, just use the following syntax:

ls file-that-does-not-exist 2>&1 | grep file

Or even better not to have on the terminal the standard error just throw it in /dev/null

ls file-that-does-not-exist 2>/dev/null

The standard open or standard streams that are automatically opened are:

  • 0 standard input
  • 1 standard output
  • 2 standard error

 

Using simple arrays in bash

With Bash to explicitly declare an array you have to use

declare -A mioarray

To have the value of element 5 just write

echo $[mioarray[5]

While to change the value you have to write

mioarray[5]='new value'

${mioarray[*]} o ${mioarray[@]} is expanded by all array values while $[#mionome[@]} is expanded with the length of the array

What can we do with the arrays? For example, store the output of a command whose line we would like to go to a different item.

IFS=$'\n' mioarray=($(ls -alh))

At this point we can print output as

 IFS=$'\n' echo "${mioarray[*]}"

Attention: Double quotes are important for not having the output on a single line.

Doing so we could do several tests on the same captured output once.

 

 

Using associative arrays in bash

To declare an associative array, you must do so

declare -A mioarray

and as an index you can use a string, this means that

mioarray[test]='aa'
echo ${mioarray[test]} # returns 'aa'

 

Leave a Reply

Your email address will not be published. Required fields are marked *