简体   繁体   English

在bash中将空间视为换行符

[英]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. 我写了一个bash只是为了显示给定目录的所有文件的名称,但是当我运行它时,它会破坏带有空格的文件名。

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 运行bash脚本时出现以下问题

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.... 我到目前为止尝试过的事情是重置IFS变量,例如IFS = $(echo -en“ \\ t \\ n \\ 0”),但没有发现任何变化。

If anyone know please help me..... 如果有人知道,请帮助我.....

Do not loop through the result of ls . 不要遍历ls的结果。 Parsing ls makes world worse (good read: Why you shouldn't parse the output of ls ). 解析ls会使世界变得更糟(请读: 为什么不应该解析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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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