我有一个需要修改的shell脚本,以返回带有相关用户ID的全名。我真的可以使用帮助详细解释如何使用正确的语法正确修改此shell脚本。如果有人可以帮助我了解如何完成这项任务,我将非常感谢您提供的任何帮助。我在这里学习,我对这个社区很新,所以如果发布错误或格式错误,请让我知道我做错了什么。提前致谢
这是所需的输出:
$ ./findName.sh eiei
SETSUNA F SEIEI
$
下面是shell脚本本身。文件/ acct / commmon / spring-names是所有用户ID和全名所在的位置。
#!/bin/sh
# findName.sh
if [ $# -eq 1 ]; then
# if there is exactly one command line arg used with the command
# do something(s).
echo "Your command line entry is: $1" > test
if [ -s ./test ]; then
cat test
else
echo "You should not see this line as output....."
fi
else
# tell the user how to use the command and exit the script
echo "usage: `basename $0` [only_one_argument]"
exit 1
答案 0 :(得分:0)
我不确定我是否理解你想要做什么,但我认为你想用$ 1 arg运行一个脚本./findName.sh
。然后该脚本将获得$ 1并在文件中搜索名称?如果我错了请纠正我,我会更新我的答案。因为你有bash标记,我做了shebang line bash。
ORIGINAL:
#!/bin/sh
# findName.sh
if [ $# -eq 1 ]; then
# if there is exactly one command line arg used with the command
# do something(s).
echo "Your command line entry is: $1" > test
if [ -s ./test ]; then
cat test
else
echo "You should not see this line as output....."
fi
else
# tell the user how to use the command and exit the script
echo "usage: `basename $0` [only_one_argument]"
exit 1
REVISION:
#!/bin/bash
# findName.sh
searchFile="/acct/commmon/spring-names"
if [[ $1 = "" ]] ; then
echo "You need to supply an argument to the script. Please rerun the script. syntax is below."
echo "./`basename $0` john"
exit 2
fi
grep -i $1 ${searchFile}
if [[ $? = "1" ]] ; then
echo "$1 was not found in ${searchFile}"
fi
出口
答案 1 :(得分:0)
给定
的文件格式First,Middle,Last,Userid
以下应该做你想要的。阅读内联评论以获取更多详细信息:
#!/bin/bash
# findName.sh
searchFile="/acct/common/spring-names"
if [[ $1 = "" ]] ; then
echo "You need to supply an argument to the script. Please rerun the script. syntax is below."
echo "./`basename $0` john"
exit 2
fi
# read the file line by line
while read LINE
do
# file format: First,Middle,Last,Userid
# set the index values based on the line format given above, change as needed.
firstNameIndex=0
middleNameIndex=1
lastNameIndex=2
userIDIndex=3
# read the line into an array
IFS=', ' read -r -a lineArray <<< "$LINE"
# if the passed parameter equals the value of the line at userIDIndex
if [[ $1 -eq ${lineArray[$userIDIndex]} ]] ; then
echo ${lineArray[$firstNameIndex]} ${lineArray[$middleNameIndex]} ${lineArray[$lastNameIndex]}
exit 1 # this assumes only one instance of a user id per file, if you expect more, than delete this line.
fi
done < "$searchFile"
您可以将它们存储在变量中以便稍后进行更多操作,而不是像在此处所做的那样回显数组值,例如
firstName=${lineArray[$firstNameIndex]}
middleName=${lineArray[$middleNameIndex]}
lastName=${lineArray[$lastNameIndex]}
给定具有以下内容的文件:
Hunter,David,Hatch,hhatch
输出结果为:
$ ./findName.sh hhatch
Hunter David Hatch