Shell script issue with filenames containing spaces

前端 未结 4 885
再見小時候
再見小時候 2021-01-19 03:54

I understand that one technique for dealing with spaces in filenames is to enclose the file name with single quotes: \"\'\".

Why is it that the following code called

相关标签:
4条回答
  • 2021-01-19 04:19

    change the following line from

    ls "'$f'"
    

    into

    ls "$f"
    
    0 讨论(0)
  • 2021-01-19 04:22

    What about this ? =)

    #!/bin/sh
    for f in *; do
        printf -- '%s\n' "$f"
    done
    
    0 讨论(0)
  • 2021-01-19 04:25

    you're actually adding redundant "'" (which your echo invocation shows)

    try this:

    #!/bin/sh
    for f in *
    do
    ls "$f"
    done
    
    0 讨论(0)
  • 2021-01-19 04:25

    Taking a closer look at the output of your echo.sh script you might notice the result is probably not quite the one you expected as every line printed is surrounded by ' characters like:

    'file-1'
    'file-2'
    

    and so on.

    Files with that names really don't exist on your system. Using them with ls ls will try to look up a file named 'file-1' instead of file-1 and a file with such a name just doesn't exist.

    In your example you just added one pair of 's too much. A single pair of double quotes" is enough to take care of spaces that might contained in the file names:

    #!/bin/sh
    for f in *
    do
      ls "$f"
    done
    

    Will work pretty fine even with file names containing spaces. The problem you are trying to avoid would only arise if you didn't use the double quotes around $f like this:

    #!/bin/sh
    for f in *
    do
      ls $f # you might get into trouble here
    done
    
    0 讨论(0)
提交回复
热议问题