我正在尝试在 bash 中创建我的第一个 shell 脚本。我已经创建了代码,并设法将脚本保存在我的主目录中,但它无法运行。首先,我尝试从主目录运行它:./testscript.sh
,并以“权限被拒绝”作为响应,然后我尝试sudo ./testscript.sh
,然后“找不到命令”。
这是我的脚本:
#!/bin/bash
mkdir -p/home/filer
touch /home/filer/fil1
touch /home/filer/fil2
touch /home/filer/fil3
tar-zcvf file.tar.gz /home/filer
所以我尝试创建一个脚本,在我的主目录中创建一个名为“filer”的目录,使用 touch 在“filer”目录中创建 3 个单独的文件,然后从整个“filer”目录中创建一个 tar.archive。我认为脚本是正确的,我可以用手运行脚本。
最佳答案
除了几个拼写错误(mkdir -p/path
-> mkdir -p/path
、tar-zcvf
... -> tar -zcvf
...)之外,您应该使用 $HOME
环境变量引用您的主目录。 /home/filer
是绝对目录路径,我假设它不是您的实际主目录。
#!/bin/bash
mkdir -p $HOME/filer
touch $HOME/filer/fil1
touch $HOME/filer/fil2
touch $HOME/filer/fil3
tar -zcvf file.tar.gz $HOME/filer
您可以将脚本 ./testscript.sh
执行为 bash testscript.sh
或 ./testscript.sh
。
在第二种情况下,脚本需要具有适当的可执行权限。 chmod +x ./testscript.sh
赋予其完全可执行权限。
关于linux - 运行第一个 shellscript 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55812813/