Bash 我该如何在Korn Shell中编写此文件?
如何在Korn Shell中重写此脚本?在Bash,对吧?我对所有外壳之间的实际差异有点困惑。。。我把它转换成Korn Shell的方法对吗Bash 我该如何在Korn Shell中编写此文件?,bash,shell,ksh,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=$(c
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
我建议将
[[
..]
替换为[
..]
,并使用-eq
/-ne
使脚本在不同的shell上更具可移植性
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
此脚本与所编写的Kornshell完全兼容。你不必对它做任何事 Kornshell和Bash确实有所不同,但在很少的地方有所不同。最常见的是:
- Kornshells有
,而Bash没有。但是,两者都有打印
printf
- Kornshell和Bash在
排版的工作方式上有所不同。Kornshell的语法要丰富得多。Bash使用其他命令来做同样的事情
- Bash有一组更丰富的命令行特性。Kornshell和Bash都有
来设置选项,但是Bash也有set-o
设置。而且,Bash具有更好的提示语法。你不会相信我必须通过设置Kornshell提示符来完成Bash中shopt
所做的事情PS=“\u@\h:\w$”
- 我相信在算术处理上也有一些不同。我只是一时想不起来
顺便说一句,这个脚本不会像您给/etc/passwd文件添加新用户时所声称的那样将用户添加到/etc/passwd文件中。快速测试和构造(
if…fi
,$(…)
似乎在ksh中工作,您尝试过吗?您尝试过将顶部的shebang行更改为#!/bin/ksh吗?我没有看到任何明显特定于bash的内容。它应该工作,或者使用set-vx
,您应该能够在5分钟内修复它。祝您好运。抱歉,[…]'在ksh中始终受支持。请参阅ksh88文档:和ksh93文档:。只需搜索'[['。祝大家好运。发布后仅19分钟,这是如何成为社区wiki的?这是S.O.的一种新的哲学。只是好奇,以前从未见过这种情况。这不是真的。Kornshell有[
和]]
测试。此特定脚本中没有任何与Kornshell不兼容的内容。我在Bash和Kornshell中成功运行了该脚本。我唯一要评论的是,该脚本声称添加了一个用户,但没有说明[[
也受ksh
支持。但我的意思是[
的可移植性不如[
@shelleter我已经决定自己将答案分享给社区wikiYea,它更像是一个虚拟脚本/example.Ksh支持浮点运算,但Bash不支持。两者都有echo
,但printf
是首选。+1