Handling variables with spaces in shell scripts (bash scripts)

Time:2020-9-23

This article mainly introduces the bash script for the treatment of files with spaces.

When processing audio files in batch, use the following script to find that the file name with space cannot be processed;

#$1: traversed folder
rootDir=$1
cd $rootDir
allAudioFile=$(find $1 -name "*\.mp3")
for oneAudioFile in $allAudioFile
do
  mv -f $oneAudioFile  $rootDir
done

Print the execution information through set – x, and find that it can be executed, but the corresponding file name cannot be found in the execution process. The source file corresponding to MV is not the original file name. Through comparison, it is found that the original file name contains spaces, which leads to the failure to extract the complete file name during the for loop;

For example, if there is a file a B.mp3, the following print will be printed in the for loop:

mv: cannot stat “./a” : No such file or directory

From the above error message, it can be found that the original file name contains spaces due to the space being interrupted. Therefore, it is necessary to recognize that the file name contains spaces during the for loop processing, so that the spaces in the file name are not processed;

Bash uses IFS variables for segmentation, so it is necessary to modify the separation method of IFS and then re isolate it. That is to say, “line breaking” should be used as the processing method


IFS=$(echo -en “\n\b”)
IFS=$(echo -en “\n\r”)

The above two methods can be used (using ubuntu16.04), and the others can be used. Just use “\ n” as one of the identifiers during processing, because using the find command or other commands will store the results in the form of lines in the variable;

#$1: traversed folder
rootDir=$1
cd $rootDir
allAudioFile=$(find $1 -name "*\.mp3")
IFS_BACKUP=$IFS
IFS=$(echo -en "\n\b")
#IFS=$(echo -en "\n\r")
for oneAudioFile in $allAudioFile
do
  mv -f "$oneAudioFile"  $rootDir
done
IFS=$IFS_BACKUP

At this point, the bash script has finished introducing the processing method of files with spaces. Of course, you should remember to save the original IFS content and put the original content back after the script runs.

summary

The above is a small introduction to the processing shell script with a space variable (bash script), I hope to help you!