Search code examples
bashvariablescut

Using cut to parse string and check if the contents exist


I'm writing a script and I have a variable MINIENTREGA_FICHEROS="informe.txt programa.c"

This variable can contain any number of files separated with a blank space. What I need to do is to check the current folder to make sure those files exist and tell the user. What I thought might be appropriate for this situation was to use cut to separate all words from each other and assign each one to a local variable. Afterwards use if [ -e $var ] inside of a for and echo the result, or something along those lines.

Any advice?


Solution

  • cut is best used when the required field(s) are previously known, i.e.to select a column/columns from text. I think, a simple do loop is much better suited here:

     MINIENTREGA_FICHEROS="informe.txt programa.c"
     for i in $MINIENTREGA_FICHEROS; do 
       [ ! -e $i ] &&  echo 'file "'$i'" is missing'
     done
    

    Output:

     file "informe.txt" is missing
     file "programa.c" is missing
    

    EDIT: To be precise, the first command is only included here to actually initialize the variable in your shell if you try out the command. If it is already present (e.g. when using it inside a script), you should omit it.