【问题标题】:Bash Script not outputting anythingBash脚本不输出任何东西
【发布时间】:2019-11-10 19:55:24
【问题描述】:

我的脚本只是运行没有输出。如果我不输入任何参数,它会正确检查错误,但如果我为参数输入适当的文件,它只会运行而没有输出也没有错误。该脚本的目标是检查文件是否可执行,然后询问用户是否要更改未设置的权限。

这里是代码

 #!/bin/bash

#making sure and argument is entered

if [ $# -ne 1 ]
then
  echo "Invalid arguments. Must pass 1 argument"
  echo "Usage: $0 <filename>"
  exit 1
fi

#filename argument variable
fname=$1

#storing file to verify its a executable
is_executable=`file $fname`

#getting permissions
lsOut=`ls -l $fname|awk '{print $1}'`

ownerPerm=`echo ${lsOut:1:3}`
groupPerm=`echo ${lsOut:4:3}`
otherPerm=`echo ${lsOut:7:3}`

# checking if the file is a executable
if [[ "$is_executable" =~ .*"executable".* ]]
then
  if [[ $ownerPerm != *"x"* ]]
  then
    choice=""
    echo "Should the execute bit be set for Owner(yes/no)? "
    read choice
    if [ $choice == "yes" ]
    then
      chmod u+x $fname
    fi
  fi

  if [[ $groupPerm != *"x"* ]]
  then
    choice=""
    echo "Should the execute bit be set for Group(yes/no)? "
    read choice
    if [ $choice == "yes" ]
    then
      chmod g+x $fname
    fi
  fi

  if [[ $otherPerm != *"x"* ]]
  then
    choice=""
    echo "Should the execute bit be set for Other(yes/no)? "
    read choice
    if [ $choice == "yes" ]
    then
      chmod o+x $fname
    fi
  fi
else
  if [[ $ownerPerm =~ .*"x".* ]]
  then
    chmod u-x $fname
    echo "Execute permission removed from owner for the file $fname"
  fi

  if [[ $groupPerm =~ .*"x".* ]]
  then
    chmod g-x $fname
    echo "Execute permission removed from group for the file $fname"
  fi
  if [[ $otherPerm =~ .*"x".* ]]
  then
    chmod o-x $fname
    echo "Execute permission removed from other for the file $fname"
  fi
fi

【问题讨论】:

  • 这似乎对我有用。试试running it with bash -x,看看它执行时发生了什么。另外,运行它通过shellcheck.net 并修复它指出的问题。我还建议简化测试(例如 if [[ $ownerPerm = *"x"* ]]if [[ $ownerPerm =~ "x" ]] 而不是 if [[ $ownerPerm =~ .*"x".* ]])。如果您无法解决,请告诉我们minimal, reproducable example
  • 我编辑了问题:一些缩进。
  • 有一种直接的方法可以检查您是否可以执行文件:[[ -x $file ]]。使用它会大大简化你的脚本。
  • 使用stat获取权限而不是解析ls的输出。
  • 你能显示输入吗?当file 返回executable 并且模式为drwxrwxrwx 时,你期望什么输出?

标签: bash shell unix scripting


【解决方案1】:

我发现这是错误的。我是个白痴,错误地为我尝试运行的测试设置了文件权限。 bash -x 命令让我弄清楚了。

【讨论】:

  • 为了其他有类似问题的人的利益,请提供修复它的权限代码。
猜你喜欢
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2020-02-21
相关资源
最近更新 更多