The selection should be based on submitting an argument when the script is executed.
#!/bin/bash #This script echoes a text and creates a file echo "welcome. Will create a file with content in this folder" ls -l | grep .txt > files_in_folder
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
Assuming that the user of the script uses an argument that is the filename suffix that they want to select filenames with, for example
#!/bin/sh printf '%s\n' ./*"$1"
This would list all names in the current directory that ends with the given filename suffix. The
printf command would take the list generate when the shell expands the pattern (which includes the argument given by the user at the end) and then output each list entry (filename in this case) on their own line according to the
printf format string. The format string used here is
%s\n, which means "some string followed by a newline character".
Would you want to use
ls -l to get a "long listing" that includes file meta-data:
#!/bin/sh ls -ld ./*"$1"
-d is needed as to not list the contents of directories matching the pattern. Again, the shell expands the given pattern and invokes
ls -ld with the list of matching filenames.
To include names in subdirectories, using
#!/bin/bash shopt -s globstar printf '%s\n' ./**/*"$1"
** pattern matches recursively into subdirectories if it's enabled with the
globstar option. You could also use
ls -ld with the above pattern, obviously, but it has the potential to break if the expansion of the pattern results in many thousands of filenames.
To restrict the list to only regular files (i.e. not directory names etc., but including hidden names), while going into subdirectories:
#!/bin/sh find . -name "*$1" -type f
-ls to the end if you require something that looks like the
ls -ld output.
This would also work even if there are many thousands of matching filenames, but now the argument can no longer contain filename globbing characters (i.e. the command above would not find files whose names end with something like the literal string
.* if you give
'.*' as the argument to the script).
In all cases, the
$1 should be quoted. In the
find command, the
* needs to be quoted too as
find does its own matching of pattern given to
-name. In the other cases,
* should be unquoted to allow the shell to expand it.
Redirect the output to a file, either inside the script or when you run it, if that is part of the requirement.
Each one of the above variations of the script would be invoked in the same way:
You use it like below : ( Note all the double quotes in the arguments passed to the script )
#!/usr/bin/bash first_cmd="$1" second_cmd="$2" $first_cmd | $second_cmd > outputfile.txt
$ ./temp.sh "ls -lrt" "grep '\.txt$'"
Check output :
$ cat outputfile.txt ***all the filename with .txt will print