-1

I want my script to find a file (in the current directory) with the first line equal to START. Then that file should have FILE <file_name> as the last line. So I want to extract the <file_name> - I use tail for this. It works ok for standard file names but cracks for nonstandard file names like a a or a+b-c\ = e with tail reporting tail option used in invalid context -- 1

Here is the beginning of the script:

#!/bin/bash

next_stop=0;

# find the first file
start_file=$(find . -type f -exec sed '/START/F;Q' {} \;)
mv "$start_file" $start_file       # << that trick doesn't work

if [ ! -f "$start_file" ]
then
  echo "File with 'START' head not found."
  exit 1
else
    echo "Found $start_file"
fi

# parse the last line of the start file
last_line=$(tail -1 $start_file)    # << here it crashes for hacky names
echo "last line: $last_line"
if [[ $last_line == FILE* ]] ; then 
    next_file=${last_line#* }
    echo "next file from last line: $next_file"
elif [[ $last_line == STOP ]] ; then
        next_stop=true;
    else
        echo "No match for either FILE or STOP => exit"
        exit 1
    fi

I tried to embrace the find output with braces this way

mv "$start_file" $start_file

but it doesn't help

micsza
  • 789
  • 1
  • 9
  • 16

2 Answers2

1

For you two examples, you need to escape space and egual in file name (with \ character), and escape escape character too. So a a have to be a\ a when passing to tail, and a+b-c\ = e have to be a+b-c\\\ \=\ e. You can use sed to make this replacement.

This example give you an better and easier way to make this replacement :

printf '%q' "$Strange_filename"
romaric crailox
  • 564
  • 1
  • 3
  • 15
  • I followed your advice with `start_file1=$(echo $start_file | sed 's/ /\\ /g')` which yields `./a\ a` for `a a` but tail still complaints invalid option --1 – micsza May 24 '17 at 07:47
1

This error is occur to the character of the escape. You should write it start_file variable in quotes. last_line=$(tail -1 $start_file) --> last_line=$(tail -1 "$start_file")

Hakan E
  • 24
  • 1