简体   繁体   中英

Treating space as newline character in bash

I have written a bash just to display the name of all the files of a given directory but when I am running this it breaking the file name which has spaces.

if [ $# -eq 0 ]
then
echo "give a source directory in the command line argument in order to rename the jpg file"
exit 1
fi

if [ ! -d "$1" ]; then
exit 2
fi

if [ -d "$1" ]
then
for i in $(ls "$1")
do
echo "$i"
done
fi

I am getting the following thing when I run the bash script

21151991jatinkhurana_image
(co
py).jpg
24041991jatinkhurana_im
age.jpg
35041991jatinkhurana_image
.jpg

The thing that i have tried till now is resetting the IFS variable like IFS=$(echo -en "\\t\\n\\0") but found no change....

If anyone know please help me.....

Do not loop through the result of ls . Parsing ls makes world worse (good read: Why you shouldn't parse the output of ls ).

Instead, you can do make use of the * , that expands to the existing content in a given directory:

for file in /your/dir/*
do
   echo "this is my file: $file"
done

Using variables:

for file in $dir/*
do
   echo "this is my file: $file"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM