简体   繁体   中英

Need to run a command in current directory only if the file is not set with executable

Here is the problem:

Use a bash for loop which loops over files that have the string "osl-guest" and ".tar.gz" in your current directory (using the 'ls' command, see sample output below), and runs the command 'tar -zxf' on each file individually ONLY IF the file is not set with executable. For example, to run the 'tar -zxf' command on the file 'file1', the command would be: tar -zxf file1

Sample output of "ls -l":

-rw-r--r--   1 lance lance   42866 Nov  1  2011 vmlinuz-2.6.35-gentoo-r9-osl-guest_i686.tar.gz
-rwxr-xr-x   1 lance lance   42866 Nov  1  2011 vmlinuz-3.4.5-gentoo-r3-osl-guest_i686.tar.gz
-rw-r--r--   1 lance lance   42866 Nov  1  2011 vmlinuz-3.5.3-gentoo-r2-osl-guest_i686.tar.gz

You can perform the loop in the following way, without the need to call ls :

# For each file matching the pattern
for f in *osl-guest*.tar.gz; do
    # If the file is not executable
    if [[ ! -x "$f" ]]; then 
            tar -zxf $f;
    fi; 
done;

The *osl-guest*.tar.gz simply uses shell expansion in order to get the list of files you want, rather than making a call it ls .

The if statement checks if the file is executble, -x is the test for an executable and the use of ! negates the result, so it will only enter the if block when the file is not executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM