bash - 将路径作为参数传递给 shell 脚本

标签 bash shell directory arguments

我编写了 bash 脚本来打开作为参数传递的文件并将其写入另一个文件。但是只有文件在当前目录中,我的脚本才能正常工作。现在我还需要打开并写入不在当前目录中的文件。

如果 compile 是我的脚本的名称,那么 ./compile next/123/file.txt 应该在传递的路径中打开 file.txt。我该怎么做?

#!/bin/sh
#FIRST SCRIPT
clear
echo "-----STARTING COMPILATION-----"
#echo $1
name=$1   # Copy the filename to name
find . -iname $name -maxdepth 1 -exec cp {} $name \;
new_file="tempwithfile.adb"
cp $name $new_file #copy the file to new_file

echo "compiling"
dir >filelist.txt
gcc writefile.c
run_file="run_file.txt"
echo $name > $run_file
./a.out
echo ""
echo "cleaning"
echo ""

make clean
make -f makefile
./semantizer -da <withfile.adb

最佳答案

你的代码和你的问题有点困惑和不清楚。

您似乎打算查找您的文件,作为脚本的参数给出,但由于maxdepth 而失败。

如果给你 next/123/file.txt 作为参数,你的 find 会给你一个警告:

find: warning: you have specified the -maxdepth option after a non-option argument -iname, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it). Please specify options before other arguments.

此外,-maxdepth 还为您提供了 find 查找文件的深度,直到它退出。 next/123/file.txt 的深度为 2 目录。

您还试图在 find 中复制给定的文件,但之后还使用 cp 复制了它。

如前所述,您的代码真的很乱,我不知道您要做什么。如果您能详细说明,我很乐意提供帮助:)。

有一些 Unresolved 问题:

  1. 如果您已经知道文件的路径,为什么还要查找该文件?您是否总是将整个路径作为参数给出?还是只是路径的一部分?只有 basename ?
  2. 您只是想将文件复制到另一个位置吗?
  3. 您的writefile.c 是做什么的?它会将您文件的内容写入另一个文件吗? cp 已经这样做了。

我还建议使用带有大写字母的变量,并检查所用命令的退出状态,例如 cpfind,以检查这些命令是否失败。

无论如何,这是我的脚本,可能会对您有所帮助:

#!/bin/sh
#FIRST SCRIPT
clear
echo "-----STARTING COMPILATION-----"
echo "FILE: $1"
[ $# -ne 1 ] && echo "Usage: $0 <file>" 1>&2 && exit 1

FILE="$1"   # Copy the filename to name
FILE_NEW="tempwithfile.adb"
cp "$FILE" "$FILE_NEW" # Copy the file to new_file
[ $? -ne 0 ] && exit 2

echo
echo "----[ COMPILING ]----"
echo
dir &> filelist.txt # list directory contents and write to filelist.txt
gcc writefile.c # ???

FILE_RUN="run_file.txt"
echo "$FILE" > "$FILE_RUN"

./a.out

echo
echo "----[ CLEANING ]----"
echo

make clean
make -f makefile
./semantizer -da < withfile.adb

关于bash - 将路径作为参数传递给 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24341686/

相关文章:

c - 打开文件时出错

file - Emacs-Lisp 中的异步复制文件和复制目录?

bash - Unix/bash。对于带有数字的文件名并行两个 for 循环

python - 使用 echo 写入文件的换行符在 shell 中有效,但在 Python 3 中为文字

linux - 在 Shell 中制作电话簿

bash - 使用 bash 删除目录中未链接的所有文件夹

bash - 在 POSIX shell 脚本中嵌入 Unicode 字符的最佳方法是什么?

linux - Docker:带有参数和引号的入口点

mysql - 如何在shell脚本中将mysql存储过程的结果转换为JSON数据?

linux - 粘贴命令不识别脚本中的换行符 (/n)