Iterating over each line of ls -l output

前端 未结 6 2044
长发绾君心
长发绾君心 2020-12-12 11:32

I want to iterate over each line in the output of: ls -l /some/dir/*

Right now I\'m trying: for x in $(ls -l $1); do echo $x; done

6条回答
  •  没有蜡笔的小新
    2020-12-12 12:21

    Set IFS to newline, like this:

    IFS='
    '
    for x in `ls -l $1`; do echo $x; done
    

    Put a sub-shell around it if you don't want to set IFS permanently:

    (IFS='
    '
    for x in `ls -l $1`; do echo $x; done)
    

    Or use while | read instead:

    ls -l $1 | while read x; do echo $x; done
    

    One more option, which runs the while/read at the same shell level:

    while read x; do echo $x; done << EOF
    $(ls -l $1)
    EOF
    

提交回复
热议问题