Posted by jyredevil.
Posted by jyredevil.
Bash Lab I
21st July 2008, Monday
With ls command , we may list out files in a directory. As example, may refer to below:
—
[root@melaka lab]# ls -al
total 8
drwxrwxr-x 2 jyredevi jyredevi 4096 Jul 29 01:58 .
drwxrwxr-x 4 jyredevi jyredevi 4096 Jul 29 01:58 ..
-rw-rw-r– 1 123 123 0 Jul 29 01:58 file1
-rw-rw-r– 1 123 123 0 Jul 29 01:58 file2
-rw-rw-r– 1 456 456 0 Jul 29 01:58 file3
—
How if we would only like to display the file with the same files ownership ? Taken above as example, if we would only like to display or list out files with ownership and group as ’123′, then may issue bash command as below:
—
[root@melaka lab]# ls -al | grep 123
-rw-rw-r– 1 123 123 0 Jul 29 01:58 file1
-rw-rw-r– 1 123 123 0 Jul 29 01:58 file2
—
Let say, we would like to change all files with ownership and group of ’123′ to ’456′ , then we would just issue bash command ‘chown 456:456 file1 file2′ . Think of situation where if there are plenty of files with ownership and group of ’123′ which would like to be changed to ’456′ , then it will be troublesome to have command ‘chown 456:456 file1 file2 file3 file4 file5 …. file(n)’ , right ?
As for above situation, you might actually list out the files with the ownership and group of ’123′ as below:
—
[root@melaka lab]# ls -al | grep 123 | awk {‘print $9′}
file1
file2
—
Why awk {‘print $9′} ? This is because this will print out only column 9 from results ‘ls -al | grep 123′ , which will only displays the file names.
To add actions those would like to perform on the files, as in this scenario , chown, then may add command as below:
—
[root@melaka lab]# ls -al | grep 123 | awk {‘print $9′} | xargs chown 456:456
[root@melaka lab]# ls -al
total 8
drwxrwxr-x 2 jyredevi jyredevi 4096 Jul 29 01:58 .
drwxrwxr-x 4 jyredevi jyredevi 4096 Jul 29 01:58 ..
-rw-rw-r– 1 456 456 0 Jul 29 01:58 file1
-rw-rw-r– 1 456 456 0 Jul 29 01:58 file2
-rw-rw-r– 1 456 456 0 Jul 29 01:58 file3
—
As you can see from the latest ls -al result, file1 and file2 ownerships have been updated to 456. You could perform other actions as well with the xargs , such as removing file by command such as ‘ls -al | grep 123 | awk {‘print $9′} | xargs rm -rf’
Yeah, lets enjoy around the bash commands .
~ Finished
« Leptospirosis Next Post
Heart Broken July… Awakening August »