Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 脚本写入文件权限被拒绝_Bash_Scripting_Ubuntu 18.04 - Fatal编程技术网

Bash 脚本写入文件权限被拒绝

Bash 脚本写入文件权限被拒绝,bash,scripting,ubuntu-18.04,Bash,Scripting,Ubuntu 18.04,我在问之前确实试着找到答案。对不起,如果这是重复的。这是一个家庭作业。我需要创建一个脚本来提取用户名,并在/etc/password中找到特定信息(用户名、主目录、shell)以显示和写入某个文件。主目录内容也应显示并写入同一文件 sudo可以工作,但我不希望它要求sudo工作 #!/bin/bash echo "This script will display your username, grab your shell and home directory, provide a list o

我在问之前确实试着找到答案。对不起,如果这是重复的。这是一个家庭作业。我需要创建一个脚本来提取用户名,并在/etc/password中找到特定信息(用户名、主目录、shell)以显示和写入某个文件。主目录内容也应显示并写入同一文件

sudo可以工作,但我不希望它要求sudo工作

#!/bin/bash
echo "This script will display your username, grab your shell and home directory, provide a list of what is in your home directory, and write this information to a file."

# assign the values to variables
usrEntry=$(grep $USER /etc/passwd)
usrName=$(echo $usrEntry|cut -f1 -d:)
usrHome=$(echo $usrEntry|cut -f6 -d:)
usrShell=$(echo $usrEntry|cut -f7 -d:|cut -f3 -d/))
usrHomeSize=$(ls $usrHome -lh|head -1)
usrHomeList=$(ls $usrHome -lh|tail --lines=+2)
outputFile="$usrHome/UserInfo.txt"

# display username, home directory, and shell
echo "Your username is $usrName"
echo "Your home directory is $usrHome"
echo "You are using the $usrShell shell"

# display contents of home directory
echo "Your home directory contents:"
ls $usrHome -lh

# write results to file, formatted
echo "The script will now append this information to the UserInfo.txt file. If this file does not exist, a new one will be created."
echo "-----New Run-----" >> $outputFile
printf "%s: %s\n" "Username" $usrName "Home Directory" $usrHome "UserShell" $usrShell >> $outputFile
echo "Home Contents" >> $outputFile
printf "%s %s\n" $usrHomeSize >> $outputFile
printf "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" $usrHomeList >> $outputFile
echo "Thank you for using my script. Maybe someday someone will find this useful"
exit 0
如果这是试图实现什么还不清楚,我可以解释更多,但我想我已经涵盖了它。我被拒绝了多行权限

/usr/local/bin/UserInfo.sh: line xx: /UserInfo.txt: Permission denied
其中xx是第25行到第29行。这些都是最重要的

printf/echo "some text" >> $outputFile

编辑:我后来发现,事实上,我不能在自己的主目录中写入或触摸任何东西,所以我必须修复这个问题,并在完成后再次检查这个脚本

编辑2:我的主文件夹归root所有。已修复,仍然无法写入文件

我认为未设置“usrHome”。 关于L15显示了什么

echo "Your home directory is $usrHome"

请看一看:不要使用
cut
解析/etc/passwd。更干净的方法是:
而IFS=:readname password UID GID GECOS directory shell;做完成
可能更喜欢
getent
而不是直接访问
/etc/passwd
。我同意所有这些,但老师希望我们使用某些工具。他承认有更好的方法,我们稍后会发现,但这正是他现在想要的。无论如何,你还是要使用
$HOME
。shell已经提供了这些信息。我同意使用$HOME作为首选项,但我应该从/etc/passwd获取它,作为从文件中提取数据的练习。忘记回答您的问题了。usrHome设置在第7行