我如何在Korn Shell中写这个?

时间:2012-01-18 21:58:07

标签: bash shell ksh

如何在Korn Shell中重写此脚本?它在Bash中对吗?我对所有炮弹之间的实际差异感到有点困惑......我是否正确地将它转换为Korn Shell?

usage ()
{
     echo      "usage: ./file.sk user"
}
# test if we have two arguments on the command line
if [[ $# != 1 ]]
then
    usage
    exit
fi

# Search for user
fullname=$(cut -f1 -d: /etc/passwd | grep "$1")
if [[ $? -eq 0 ]]; then
                echo "User already found:"
                grep $1 /etc/passwd
        exit
        else
                #get numbers
                cat /etc/passwd | gawk -F: '{print $3}' | sort -n > currentuid4
                #get last number
                last=`tail -1 currentuid4`
                echo last $last
                #add +1
                newuid=`expr $last + 1`
                #print it
                echo "ADDED: $1 with UID: $newuid"
        exit
fi

2 个答案:

答案 0 :(得分:2)

此脚本完全与Kornshell兼容。你不需要做任何事情。

Kornshell和Bash确实有所不同,但在很少的地方。最常见的是:

  • Kornshells有print而Bash没有。但是两者都有printf
  • Kornshell和Bash在typeset的工作方式上有所不同。 Kornshell有更丰富的语法。 Bash使用其他命令来做同样的事情。
  • Bash拥有更丰富的命令行功能。 Kornshell和Bash都有set -o来设置选项,但Bash也有shopt设置。而且,Bash有更好的语法提示。你不会相信我必须通过设置我的Kornshell提示来执行PS="\u@\h:\w$ "在Bash中的操作。
  • 我相信算术处理也存在一些差异。我无法想到这一点。

顺便说一下,这个脚本不会将用户添加到/ etc / passwd文件中,因为它为您提供新用户时声明了。

答案 1 :(得分:0)

我建议用[[ ... ]]替换[ ... ]并使用-eq / -ne制作脚本在不同的贝壳上更便携。

usage ()
{
     echo      "usage: ./file.sk user"
}
# test if we have two arguments on the command line                                                                                                            
if [ "$#" -ne 1 ]
then
    usage
    exit
fi

# Search for user                                                                                                                                              
fullname=$(cut -f1 -d: /etc/passwd | grep "$1")
if [ "$?" -eq 0 ]; then
                echo "User already found:"
                grep $1 /etc/passwd
        exit
        else
                #get numbers                                                                                                                                   
                cat /etc/passwd | gawk -F: '{print $3}' | sort -n > currentuid4
                #get last number                                                                                                                               
                last=`tail -1 currentuid4`
                echo last $last
                #add +1                                                                                                                                        
                newuid=`expr $last + 1`
                #print it                                                                                                                                      
                echo "ADDED: $1 with UID: $newuid"
        exit
fi