help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] if exist


From: Pierre Gaston
Subject: Re: [Help-bash] if exist
Date: Sat, 13 May 2017 07:54:45 +0300

On Sat, May 13, 2017 at 4:21 AM, Val Krem <address@hidden> wrote:

> Hi all,
>
>
> I have list of files in a given folder  and some of these files are ending
> with any digit(starting from 1 up to may be  9 or more). My aim is if a
> file name is ending with any digit number then I want copy it to other
> folder and suppress the error message generated if the file does not exist
> in the folder.
>
> Sample of list of  files
> xbx1.txt1
> xby2.txt2
> xcx3.txt3
> xxx1.txt4
> xxy1.txt5
>
> Below is my attempt.
>
> There are many problems, I'll comment on the ones more relevant to your
immediate problem

> #! /bin/bash
>
> dat0=/data/val1
> dat1=/data/val2
> shopt -s extglob
> cd ${dat0}
> xc=$(ls x*'.'txt{1..10})
> echo $xc
>
> for i in $(xc);do

This doesn't work at all, $( ) will run a command named "xc" it would have
worked a
bit better if you have used $xc which would have expanded the variable and
loop on each word.
However there is a much cleaner and simpler way:

xc=( x*.txt{1...10) # this create an array variable with the file matching
for i in "address@hidden";do  # this will loop on the elements of the array. 
note
the " "


>     if [  ${xc}  ];then
>

This tests if the variable ${xc} is a string with characters, not if the
file exists.
So first you want to test "$i" since "xc" contains all the filenames, i is
the variable
that gets the individual filenames.
then you want to test if the file exists for this you need to use the "-e"
or "-f" test:

if [ -e "$i" ]; then  #again note the double quotes they avoid problems
with spaces, glob etc.



>        cp ${xc} $dat1
>

here you want $i again
cp "$i" "$dat1"


>     fi
> done
>
>
to sum up:
#! /bin/bash

dat0=/data/val1
dat1=/data/val2
shopt -s extglob

if ! cd "${dat0}"; then
   echo "could not change directory to $dat0"
fi
xc=(x*'.'txt{1..10})
echo "address@hidden"

for i in "address@hidden";do
    if [  -e "${i}"  ];then
       cp "$i" "$dat1"
    fi
done

Some links you may want to check:

http://mywiki.wooledge.org/BashGuide
http://mywiki.wooledge.org/BashPitfalls
http://mywiki.wooledge.org/BashFAQ
http://www.shellcheck.net/


reply via email to

[Prev in Thread] Current Thread [Next in Thread]