1

I'm trying write a script which requires user interaction. Basically, the script has to ask user about 3 parameters: name of the file(s) which user wants to find, the number of days during which the file(s) were modified and the name of a tar archive. When all parameters are known script must find the appropriate files and make them into an archive with a given name. When I write a single command into the terminal:

find -name 'zad*' -mtime -10 | tar -cvf archive.tar.gz -T -

it works good. How can I use a variable entered by a user to invoke the command which is in the same script? My script is making an empty archive.

My script:

echo "Enter a number of days"
read days
echo "Enter the name of file"
read nameoffile
echo "Enter the name of tar archive"
read nameofarchive
find -name '"$nameoffile"' -mtime -"$days" | tar -cvf "$nameofarchive".tar.gz -T -
0

In general, needing user interaction is a very bad idea. it makes your script impossible to automate and it makes it very hard for your users to use since they need to manually type things out in an environment that doesn't allow tab completion.

Since @maulinglawns already explained why your script was failing, I will give you a simpler way of doing it that doesn't require your users to laboriously type out information:

#!/usr/bin/env sh

days="$1"
nameoffile="$2"
nameofarchive="$3"
find -name "$nameoffile" -mtime -"$days" | tar -cvf $nameofarchive".tar.gz -T -

Then, to find files named foo.txt, modified in the last 3 days and archive them to bar.tar.gz`, you would run:

script.sh 3 foo.txt bar

You could also add some simple error checking to ensure that the script is always run with the correct number of parameters:

#!/usr/bin/env sh

if [ $# -ne 3 ]; then
    echo "You need to enter three arguments"
    exit 1
fi

days="$1"
nameoffile="$2"
nameofarchive="$3"
find -name "$nameoffile" -mtime -"$days" | tar -cvf $nameofarchive".tar.gz -T -
2

Try removing the extra ' quotes in '"$nameoffile"'

Example:

maulinglawns@debian-HP:~$ read nameoffile
myFile
maulinglawns@debian-HP:~$ echo '"$nameoffile"'
"$nameoffile"
maulinglawns@debian-HP:~$ echo "$nameoffile"
myFile

If you need single quotes, escape them like this:

echo \'$nameoffile\'
'myFile'
  • Such a simple solution... I hadn't thought about that, thanks! – Ensz Oct 23 '16 at 12:20
  • @Ensz No problem. Quotes in Bash can be difficult. – maulinglawns Oct 23 '16 at 12:21
0

read supports naming variables, for example;

#!/bin/bash

read -p "How many files? (0-100) " VAR_NUMBER_OF_FILES
read -p "How many days? (0-100) " VAR_NUMBER_OF_DAYS
read -p "Tar file name? " VAR_TAR_NAME
...
find -name '"$VAR_NUMBER_OF_FILES"' -mtime -"$VAR_NUMBER_OF_DAYS" | tar -cvf "$VAR_TAR_NAME".tar.gz -T -

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.