将存储的路径作为变量传递

时间:2018-10-29 14:01:07

标签: bash

我正在尝试将存储在here中的变量中的路径传递给bash脚本。如果我致电./my_program.sh input.txt,应该怎么做?我尝试了几种配置,但没有成功。你有什么建议?

#!/bin/bash  

export VAR=/home/me/mydir/file.c
export DIR=${VAR%/*}

a_file_in_the_same_directory_of_the_input=file generated from preprocessing of $1  

foo(){
    ./my_function.x "$DIR/a_file_in_the_same_directory_of_the_input"
}

foo "$DIR/a_file_in_the_same_directory_of_the_input" > "$1_processed"

即,我将文件my_program.sh交给input.txt。因此,将生成一个临时文件:a_file_in_the_same_directory_of_the_input。它在输入的同一文件夹中。如何通过将文件夹的路径与新生成的文件的名称组成来将其传递给foo?这是为了确保该程序始终能够读取临时文件,而不管调用该文件的目录是什么。

1 个答案:

答案 0 :(得分:0)

使用readlink获取文件的“完整路径”(即规范文件名)。使用dirname从规范文件名中删除文件名,仅保留目录路径。

DIR=$(dirname "$(readlink -f "$1")")
echo "$DIR" is the same directory as "$1" file is/would be in.

请注意,该readlink也将适用于不存在的文件。

#!/bin/bash  

# this is a global variable visible in all functions in this file (unless not)
same_dir_as_input_txt=$(dirname "$(readlink -f "$1")")

foo(){
    ./my_function.x "$1"
}

# I use basename, in case $1 has directory path, like dir/input.txt
foo "$same_dir_as_input_txt/a_file_in_the_same_directory_of_the_input" > "$same_dir_as_input_txt/$(basename $1)_processed"

# ...... or as argument ....

foo() { 
     local argument_file="$1"
     local output_file="$2"
     ./my_function.x "$argument_file" > "$output_file"
}

foo "$same_dir_as_input_txt/a_file_in_the_same_directory_of_the_input" "$same_dir_as_input_txt/$(basename $1)_processed"

# .... or maybe you want this? .....

foo() {
    local same_dir_as_input_txt=$1
    local input_filename=$2
    # notice that the `_` is glued with the variable name on expansion
    # so we need to use braces `${1}_processed` so the shell does not expand `${1_processed}` as one variable, but expands `${1}` and then adds to that the string `_processed`
    ./my_function.x "$same_dir_as_input_txt/a_file_in_the_same_directory_of_the_input" > "$same_dir_as_input_txt/${input_filename}_processed"
}

foo "$same_dir_as_input_txt" "$(basename "$1")"