Story of a snippet: Linux one liner bash code to detect file or directory from a given list

Posted on Posted in Snippets

story-of-a-snippet-1

Today we want to go deep into a snippet posted by one of the most active users on snip2code: lbottaro. We’ll let him to explain how to use his snippet. Obviously, we used the Snip2Code embed feature to include the code in this post. 🙂

[iframe id=”embedFrame” style=”width: 600px; height: 120px;” src=”http://www.snip2code.com/Embed/27077/Linux-one-liner-bash-code-to-detect-file”]

In Linux OS developers often need to deal with full path strings at run time in their shell scripts.

This one-liner bash code shows how to check whenever the current full path is actually the path of a file or a directory.

In this case the snippet uses the output of the tree command (which returns the full path name of files or directories) as input parameter to the xargs command.

Tree output looks like the following:
./test_garbage/KU9P/gen/dd1/ff1.file
./test_garbage/KU9P/gen/file1.file
./test_garbage/juR6
./test_garbage/juR6/gen

Some lines refer to a file, some other to a directory.

Using pipe ( | ) you can concatenate the tree command output lines to the xargs command and elaborate each line at a time.

The -I option allows xargs to replace occurrences of ‘{}’ in the initial-arguments with names read from standard input. This allows to refer to the current item passed with the ‘{}’ syntax, simplifying notation, into the next instructions.

Once xargs has the reference to the current value, the full path is finally passed to a shell command, via ‘{}’ reference, invoked by option ‘sh -c’.

With the syntax ‘sh -c ” ‘ xargs allows to execute the within single quotes as shell command for each item currently selected.

In this case, the ‘if []; then else; fi’ statement allows to define a specific logic in case the current path is related to a file or directory.

This code is also interesting because does not affect the original format of the tree command lines.

Of course a one-liner may be not easy to read but is pretty useful when you need a short notation or just need to collapse many shell commands into a single line of code.

If you want to see the original snippet click here.

3 thoughts on “Story of a snippet: Linux one liner bash code to detect file or directory from a given list

  1. Hi there this is kind of of off topic but I was
    wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding know-how so I wanted to get advice from someone with experience.
    Any help would be enormously appreciated!

  2. I don’t even understand how I finished up right here, however I thought this post was good.
    I do not recognise who you are however definitely you’re going to
    a well-known blogger if you aren’t already. Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *