在 bash 中运行脚本时出错

在 bash 中运行脚本时出错

我在 bash 中编写了一个脚本来创建别名,但由于某种原因,它在某些情况下不起作用。以下是代码:

#!/bin/bash
#Script to create unique and permanent aliases

_add_alias()
{
    echo "alias $1='$2'" | sudo tee -a $HOME/.bash_aliases
    echo "Alias successfully created"
}

if [ `cat $HOME/.bash_aliases | grep "alias $1=" | wc -l` == 0 ]
    then
    if [ $# -eq 2 ]
        then
        if [ -f "$2" ] #This condition is always false, don't know why.
            then
            _add_alias $1 "$2"
        elif $2 > tmp.txt 2> tmp.txt
            then
            _add_alias $1 "$2"
        else
            echo "Wrong command"
        fi
        rm tmp.txt
    elif [ $# -gt 2 ]
        then
    echo "Error: Usage: addal alias_name 'command' (comand between quotes)"
    elif [ $# -lt 2 ]
        then
        echo "Wrong number of parameters"
    fi
else
    echo "Alias name already exists"
fi

我希望你能帮助我修复脚本。

答案1

这是你的错误(来源):

  • SC2002无用的 cat。请考虑使用 'cmd < file | ..' 或 'cmd file | ..'。
  • SC2006使用 $(..) 代替传统的 `..`。
  • SC2046引用此内容以防止单词分裂。
  • SC2086双引号可以防止通配符和单词分割。
  • SC2126 考虑使用 grep -c 而不是 grep|wc。

   1  #!/bin/bash
   2  #Script to create unique and permanent aliases
   3  
   4  _add_alias()
   5  {
   6      echo "alias $1='$2'" | sudo tee -a $HOME/.bash_aliases
                                             ^––SC2086 Double quote to prevent globbing and word splitting.
   7      echo "Alias successfully created"
   8  }
   9  
  10  if [ `cat $HOME/.bash_aliases | grep "alias $1=" | wc -l` == 0 ]
           ^––SC2046 Quote this to prevent word splitting.
           ^––SC2006 Use $(..) instead of legacy `..`.
                ^––SC2086 Double quote to prevent globbing and word splitting.
                ^––SC2002 Useless cat. Consider 'cmd < file | ..' or 'cmd file | ..' instead.
                                      ^––SC2126 Consider using grep -c instead of grep|wc.
  11      then
  12      if [ $# -eq 2 ]
  13          then
  14          if [ -f "$2" ] #This condition is always false, don't know why.
  15              then
  16              _add_alias $1 "$2"
                             ^––SC2086 Double quote to prevent globbing and word splitting.
  17          elif $2 > tmp.txt 2> tmp.txt
  18              then
  19              _add_alias $1 "$2"
                             ^––SC2086 Double quote to prevent globbing and word splitting.
  20          else
  21              echo "Wrong command"
  22          fi
  23          rm tmp.txt
  24      elif [ $# -gt 2 ]
  25          then
  26      echo "Error: Usage: addal alias_name 'command' (comand between quotes)"
  27      elif [ $# -lt 2 ]
  28          then
  29          echo "Wrong number of parameters"
  30      fi
  31  else
  32      echo "Alias name already exists"
  33  fi

答案2

这是经过更正和改进的脚本:

#!/bin/bash

###################################################
## Script to create permanent and unique aliases ##
###################################################

## alias is equal to the first argument.
alias="$1"

## command is equal to an array holding all
## the positional parameters minus the first.
## (i.e. for "ls -la" it would be ["ls, "-la"]).
command=("${@:2}")

## If .bash_aliases exists, load it. Now the alias check
## will take in account any alias not sourced yet on the current shell.
test -f ~/.bash_aliases && source $_

## If there are less than 2 parameters, prints the usage and exits.
if [ $# -lt 2 ]; then
    echo "Usage: $0 <alias_name> <command>"
    exit 1
fi

## If the command is not valid, prints an error and exits.
if ! type "${command[0]}" &> /dev/null; then
    echo "Wrong command"
    exit 3
fi

## If the current alias already exists, prints a error message and then exits.
if [[ "$(type -t '$alias')" == "alias" ]]; then
    echo "This alias alredy exists"
    exit 2
fi

## Append the alias to the .bash_aliases file.
echo "alias $alias='${command[@]}'" >> ~/.bash_aliases

## Print a sucess message.
echo "Alias '$alias' linked to the command '${command[@]}'!" 

我改变的事情:

  • 注释代码。
  • 用于type确定别名是否已经存在。
  • 删除了该功能,因为我认为没有必要。
  • 用于type确定命令是否有效。
  • 删除了一些不必要的elif
  • 改善了条件。
  • command可能不加引号(即myscript pingoogle ping google.com

答案3

一些想法:

myscript alias1 "$HOME/dir/ascript"

将在测试部分评估

[ -f '/home/me/dir/ascript' ]

这可能是真的,也可能是假的。

myscript alias2 '$HOME/dir/anotherscript'

将在测试部分评估

[ -f '$HOME/dir/ascript' ]

这始终是错误的(除非您在本地目录中有一个名为 $HOME 的目录)。

myscript alias3 "$HOME/dir/sample.sh foo bar"

将在测试部分评估

[ -f '/home/me/dir/sample.sh foo bar' ]

这是错误的,除非其中有一个“sample.sh foo bar”文件/home/me/dir

你应该修复.bash_aliases并使用

echo "alias $1='$2'" >> $HOME/.bash_aliases

相关内容