0

I am trying to pass a path, stored in a variable as we found here to a bash script. How should it be done, if I call ./my_program.sh input.txt with? I tried several configurations, without succes. What do you suggest?

#!/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"

Namely, I give to my_program.sh the file input.txt. Hence, a temporary file is produced: a_file_in_the_same_directory_of_the_input. It is in the same folder of the input. How can I pass it to foo, by composing the path of the folder with the name of the newly generated file? That's to be sure that the program will always be able to read the temporary file regardless of the directory it is called from.

Worice
  • 3,847
  • 3
  • 28
  • 49

1 Answers1

0

Use readlink to get "full path" (ie. canonical file name) of a file. Use dirname to remove the filename from the canonical file name, leaving only directory path.

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

Note, that readlink will also work on nonexisting files.

#!/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")"
KamilCuk
  • 120,984
  • 8
  • 59
  • 111