Bash Index : R - The 'R' Bash commands : description, flags and examples

return

Usage :

return n

Since return outputs "return codes", it allows calling a function and processing its return value with && and ||.

Example :

#!/usr/bin/env bash

returnSomething() {
	return $1
	}

trueThenReturnSomething() {
	true
	return $1
	}

falseThenReturnSomething() {
	false
	return $1
	}

returnTrue() {
	true
	return
	}

returnFalse() {
	false
	return
	}

for testValue in 0 1 2 42 '' x; do
	returnSomething $testValue
	returnedValue1=$?
	trueThenReturnSomething $testValue
	returnedValue2=$?
	falseThenReturnSomething $testValue
	returnedValue3=$?
	echo -e "test value : '$testValue'\treturned values : '$returnedValue1'\t'$returnedValue2'\t'$returnedValue3'\n"
done

echo
returnTrue && echo 'returned TRUE' || echo 'returned FALSE'
returnFalse && echo 'returned TRUE' || echo 'returned FALSE'
test value : '0'	returned values : '0'	'0'	'0'

test value : '1'	returned values : '1'	'1'	'1'

test value : '2'	returned values : '2'	'2'	'2'

test value : '42'	returned values : '42'	'42'	'42'

test value : ''		returned values : '0'	'0'	'1'

./test.sh: line 4: return: x: numeric argument required
./test.sh: line 9: return: x: numeric argument required
./test.sh: line 14: return: x: numeric argument required
test value : 'x'	returned values : '2'	'2'	'2'

returned TRUE
returned FALSE

read

Usage :

Read one line from the standard input or from a file, and assign the read value to a variable

Flags :

Flag Usage
-a myArray "explode" substrings of the parameter into elements of myArray. Consider IFS to identify such substrings
-p prompt variableName An example is worth 1000 words :
read -p "What's your name ? " yourName; echo "Hello $yourName"
What's your name ? Bob
Hello Bob
-r raw input : disables interpretation of backslash escapes and line-continuation in the read data

Example :

Read columns (source) :

This can be done by specifying several variables when calling read :
  • string='foo bar baz'; read a b c <<< "$string"; echo "$a $b $c"
  • text='one two three'; read -r col1 col2 col3 <<< "$text"; printf "col1: %s, col2: %s, col3: %s\n" "$col1" "$col2" "$col3"

Read data fields from a formatted text file :

tmpFile=$(mktemp tmp.XXXXXXXX); for i in {1..5}; do echo "${i}_1 ${i}_2 ${i}_3" >> "$tmpFile"; done; cat "$tmpFile"; while read itemA itemB itemC; do echo -e "$itemA\t$itemB\t$itemC"; done < "$tmpFile"; rm "$tmpFile"

Pop a group of lines from a file :

This will transpose this :
a
b
c

z
into this :
a	b	c
d	e	f
g	
y	z
tmpFile=$(mktemp tmp.XXXXXXXX); echo {a..z} | tr ' ' '\n' > "$tmpFile"; while true; do read a || break; read b; read c; echo -e "$a\t$b\t$c"; done < "$tmpFile"; rm "$tmpFile"

runlevel

Display the previous and the current runlevels. If no previous runlevel is known, it will just display N.
On older systems (?), this information may be available in the RUNLEVEL and PREVLEVEL environment variables.

resize2fs

Usage :

resize2fs [options] device size
Resize ext2, ext3, or ext4 file systems. It can be used to enlarge or shrink an unmounted file system.
If size parameter is not specified, it will default to the size of the partition.

Flags :

Flag Usage
-f force resize2fs to proceed with the filesystem resize operation, overriding some safety checks it normally enforces

Example :

Shrink a partition :

resize2fs /dev/mapper/myLVM-homes 1800G

renice

Usage :

renice newNiceValue -p PID
Alter niceness (priority) of running processes. Instead of renice-ing a new process, it is wiser to nice it at startup.
Non-root users :
  • can only renice their own processes
  • can only increase the nice value (i.e. decrease priority) of a process (see example)

Flags :

Flag Usage
-n newNiceValue
  • set the new nice value to newNiceValue
  • A niceness of −20 is the highest priority and 19 is the lowest priority. The default niceness a of process is inherited from its parent process, usually 0.
  • The -n is optional, but must be the 1st argument when used.
-p PID

Example :

Read the nice value of a process :

Playing with renice :

sleep 3 & renice 5 -p $!
[1] 19145
19145 (process ID) old priority 0, new priority 5
sleep 3 & renice -n 5 -p $!
[1] 19167
19167 (process ID) old priority 0, new priority 5
Same as above since -n is optional.
sleep 3 & renice 5 -p $!; renice 5 -p $!
[1] 19208
19208 (process ID) old priority 0, new priority 5
19208 (process ID) old priority 5, new priority 5
You can not renice an already reniced process (or at least, not like this).
sleep 3 & renice +5 -p $!; renice +5 -p $!
[1] 19251
19251 (process ID) old priority 0, new priority 5
19251 (process ID) old priority 5, new priority 5
The + sign seems to make no big difference.
sleep 3 & renice 5 -p $!; renice 1 -p $!
[1] 19272
19272 (process ID) old priority 0, new priority 5
renice: failed to set priority for 19272 (process ID): Permission denied

  • The value we specify is NOT an increment, it's the expected value (see this example).
  • Only root can decrease a nice value (i.e. give higher priority to a process).

sleep 3 & renice 5 -p $!; renice 6 -p $!
[1] 20538
20538 (process ID) old priority 0, new priority 5
20538 (process ID) old priority 5, new priority 6

Usage :

readlink mySymLink
return the target of the symbolic link mySymLink
readlink -f myFile
return the absolute path of myFile (source)

rm

Flags :

Flag Usage
-i ask for confirmation before deleting each target file
-f force delete
-r delete recursively

Example :

/bin/rm: Argument list too long (source) :

  • cd directory; find . -name '*' -type f | xargs rm
  • cd directory; find . -name '*' -type f -delete

rename

Usage :

Rename files : rename from to files will rename the specified files by replacing the first occurrence of from in their name by to.

Example :

The from / to method :

Given the files foo1, ..., foo9, foo10, ..., foo234, the commands :
  • rename foo foo0 foo?
  • rename foo foo0 foo??
will turn them into foo001, ..., foo009, foo010, ..., foo234.

Replace all spaces by underscores in filenames :

rename 's/ /_/g' *

Replace some substrings while keeping others, using callbacks :

The regular expressions have a callback syntax to refer to a "previously matched substring". In other tools (sed, Emacs, Vi, ...), such callbacks are written \n (n being the number of the matched expression, starting at 1). Even though rename accepts this syntax, it will complain saying it prefers them specified using the $ sign : $n. Example :
touch /tmp/file_01.txt; rename 's/(^.*_)..(\.txt)/${1}02$2/' /tmp/file_01.txt; ls -l /tmp/file_*
  • Here, curly braces are used to callback to the 1st matched expression because the following characters are digits, and we don't want this reference to be interpreted as the 102nd matched expression.
  • rename prefers the $n syntax, but we mustn't forget that a $ sign within double quotes will be expanded by the shell interpreter (Bash or others).

Nice numbering of ordered files :

Let's consider the set of files produced by :
prefix='testFile_'; extension='.ext'; for i in {1..20}; do touch "$prefix$i$extension"; done
For the files 1 to 9 to be numbered 01 to 09, just run :
prefix='testFile_'; rename 's/_([0-9]\.)/_0$1/g' $prefix*
  • $prefix is used to avoid affecting all files with a rename regExp *
  • the substring to match for re-use must be enclosed by ( ) (no need to escape parens), and is recalled as $n (not \n), n being the nth matched substring
This hack _may_ turn useless with : {01..20}

Rename and number a collection of files :

Let's consider a collection of files :
  • file names are not consistent
  • extensions are not consistent either : mp3/MP3, jpg/jpeg/JPG, ...
  • files have no numbering
  • the relative numbers of files are not important
... in which we would like to decrease entropy. To do so, let's :
  • rename files based on a pattern
  • number files
Let's do it with :
prefix='myFile - '; extension='.jpg'; fileNb=1; for i in *; do rename "s/^.*$/$prefix$fileNb$extension/g" "$i"; fileNb=$((fileNb+1)); done; rename 's/ ([0-9]'$extension')/ 0$1/g' *
The rename after the for loop is to re-arrange file numbers nicely.