创建文件shell脚本

时间:2013-03-24 22:01:30

标签: linux shell

我不熟悉Linux中的shell脚本,我试图从键盘获取数据,然后将传入的数据附加到文件中。非常直接但我在尝试创建文件时遇到错误。错误显示“您无权创建此文件”。

我首先检查以确保文件存在。如果存在,则追加到文件末尾。如果没有,请创建该文件。我究竟做错了什么?

谢谢!

P.S。在这种情况下,我还没有创建文件

#!/bin/sh                                                                                                                            

echo "Please enter your first name";
read first
echo "Please enter your last name";
read last

combine=":$first $last"
file="/testFile.dat"

if [ -f "$file" ]
then
echo "$file found."
echo $combine >> $file
else
echo "$file not found. Will create the file and add entry now."
touch $file
$combine >> $file
fi

2 个答案:

答案 0 :(得分:3)

您正在根目录下创建文件。尝试file="~/testFile.dat"在您的家中创建文件,或仅file="./testFile.dat"在当前目录中创建该文件。

答案 1 :(得分:3)

您正在尝试写入位于根目录/testFile.dat中的文件/。作为普通用户,您很可能没有创建此类文件的写入权限。

但是我想要的是在当前目录中创建testfile.dat

替换以下行:

file="/testFile.dat"

使用:

file="./testFile.dat"
相关问题