【问题标题】:Script bash chmod in a cicle在一个圆圈中编写 bash chmod 脚本
【发布时间】:2016-06-26 23:10:19
【问题描述】:

我希望该脚本在我引入目录时执行 cicle,并要求我在那里的每个文件更改 perm 。为什么这个输出总是找不到“文件”?但文件存在

fucntion permi {

    echo "What is the path of the file? the introduce the name of the file:"

    read DIRECT

    file=`ls -l ${dir} | cut -f 9 -d " "`

    while read file
    do

        echo "[u|g|o]"

        read who

        echo "[r|w|x]"

        read ans

        chmod ${who}+${ans} $file

    done

}

【问题讨论】:

  • 能否请您举例说明输入和预期输出?
  • 示例:我在 dir /tmp 中有一个文件 text1,他读取文件并显示 echo ugp,我写 ug,然后 r|w|x,我写 wx,然后使用 chmod我写的输入像 chmod ug+wx text1 @mebada
  • circle = 迭代或循环 .. 请在您的帖子中验证以更清楚

标签: linux bash


【解决方案1】:

你可以试试这个

fucntion permi {

echo "What is the path of the file? the introduce the name of the file:"
# read path from user with pattern .. eg (/home/mebada/test/* for all files, /home/mebada/test/*txt for all text files) 

read path 

# here I am iterating over the list of directory files .. no need to cut because I am just ls without ls long format (ls -l)
for myFile in `ls  $path`;  do
    # showing file current permission
    ls -l ${myFile}
    echo 
    echo "[u|g|o]"
    echo 
    read who

    echo "[r|w|x]"

    read ans
    #change file permission 
    chmod ${who}+${ans} $myFile

    # show after permission 
    ls -l $myFile
    echo 
    #Separator between two files
    echo " ---- "
  done
 }

【讨论】:

  • 您能解释一下您的解决方案吗?
  • 嗨罗伯特,我添加了 cmets,,还有什么需要澄清的吗?
【解决方案2】:

这里有四个主要问题。首先,ls -l ${dir} | cut -f 9 -d " " 确实 生成文件名列表。它从长格式ls 列表中挑选出第 9 个“字段”,但这可能是也可能不是文件名,具体取决于 ls -l 打印的内容。在我的 Mac 上,它主要打印日期字段的一部分。一般parsing ls is a bad idea,解析ls -l就更差了。有更好的方法来做到这一点。

其次,循环 (while read file) 不会像您想要的那样做任何事情。它的作用是从标准输入中读取行(通常,这意味着它会等待用户输入某些内容),并将读取的内容放入变量file(替换ls -l ${dir} | cut -f 9 -d " " 的输出)。你想要做的是变量file读取,而不是那个变量。

第三个问题是,在处理您找到的文件时(例如chmoding 他们),您需要提供目录路径文件名,例如chmod ${who}+${ans} $dir/$file

但是有一种更好的方法可以同时解决所有这三个问题。只需使用for file in "${dir}"/*。通配符将扩展为${dir} 中的文件列表(包括目录路径),而不会出现处理ls 输出的任何麻烦。

第四个主要问题是您没有告诉用户您请求哪个文件的权限;脚本只是一遍又一遍地询问“[u|g|o]”和“[r|w|x]”,而没有说明它将应用于哪个文件。

我还有三个小建议:function 关键字是非标准的;定义函数的更标准方法是使用括号:permi() { ...。此外,不要使用echo 提示输入,而是使用read -p 来打印提示。最后,最好在变量引用周围加上双引号,以免它们包含空格或其他一些特殊字符时出现问题。通过所有这些更改,我得到了以下结果:

permi() {

    read -p "What is the path of the file? the introduce the name of the file: " dir

    for file in "$dir"/*; do

        echo "New permissions for $file:"
        read -p "[u|g|o] " who
        read -p "[r|w|x] " ans

        chmod "${who}+${ans}" "$file"

    done

}

【讨论】:

    【解决方案3】:

    当我运行ls -l | cut -f 9 -d " " 时,我得到一些空白字段,一些年份或个位数。我建议只使用ls(不带-l)来获取文件名,因为无论如何您似乎只关心文件名,而不关心ls -l 打印的其他任何内容。

    然后在更改权限时引用文件名(chmod ... "$file"),以防有空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2020-02-10
      • 2013-09-29
      • 2012-11-12
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多