0

I want to read a list of file names stored in a file, and the top level directory is a macro, since this is for a script that may be run in several environments. For example, there is a file file_list.txt holding the following fully qualified file paths:

$TOP_DIR/subdir_a/subdir_b/file_1
$TOP_DIR/subdir_x/subdir_y/subdir_z/file_2 

In my script, I want to tar the files, but in order to do that, tar must know the actual path. How can I get the string containing the file path to expand the macro to get the actual path? In the code below the string value echoed is exactly as in the file above. I tried using actual_file_path=`eval $file_path` and while eval does evaluate the macro, it returns a status, not the evaluated path.

for file_path in `cat $input_file_list`
do
    echo "$file_path"
done
yamex5
  • 195
  • 1
  • 11

2 Answers2

1

With the tag ksh I think you do not have the utility envsubst.
When the number of variables in $input_file_list is very limited, you can substitute vars with awk :

awk -v top_dir="${TOP_DIR}" '{ sub(/$TOP_DIR/, top_dir); print}' "${input_file_list}"
Walter A
  • 19,067
  • 2
  • 23
  • 43
0

I was using eval incorrectly. The solution is to use an assignment on the right side of eval as follows:

for file_path in `cat $input_file_list`
do
    eval myfile=$file_name
    echo "myfile = $myfile"
done

$myfile now has the actual expansion of the macro.

yamex5
  • 195
  • 1
  • 11
  • 1
    You would like to find an answer without `eval` in view of special characters and possible commands. `This 'filename' is nice`. – Walter A Aug 19 '21 at 19:12
  • @WalterA Are you saying that using eval is a security problem or something else? – yamex5 Oct 30 '21 at 19:55
  • 1
    Both. Test what happens when your filename has spaces and quotes (incorrect assignments). I can't see where you set a value for `file_name`, consider the next example: `touch important_file; file_name='file$(rm importantfile)name'; eval myfile=$file_name; ls important_file` – Walter A Oct 30 '21 at 20:50