Bash script that creates an array from ls?

I am creating a bash script that will list the files (in this case apache sites are available). Listing files is easy for my ultimate goal - to take each of these files into an array, display them to the user and allow the user to choose which "file" to process, in which case he should include the site.

I'm not very far, I know that I need to set ls as an array, and then encode the action:

array=$(ls) for sites in $array(2) do echo "$sites" done 

I know that I need to index each of the files in a directory, and then allow the user to enter a number to include. So it will look like this:

 (1) newdomain.com (2) newdomain2.com Which site would you like to enable (ie 1)? 

Hope this makes sense?

+6
source share
3 answers

You could save yourself a lot of re-implementation by using the built-in select function.

The select construct makes it easy to create menus. It has almost the same syntax as the for command:

 select name [in words ...]; do commands; done 

The list of words following in is expanded, generating a list of elements. A set of extended words is printed in a standard error output stream, each of which is preceded by a number. If the in words parameter is omitted, the positioning parameters are printed as if in " $@ " were specified. The PS3 prompt is then displayed, and the line is read from standard input. If the line consists of a number corresponding to one of the displayed words, then the value name set to this word. If the line is empty, words and words are displayed again. If the EOF is read, the select command completes. Any other reading of the value causes name to be null. The reading of the string is stored in the REPLY variable.

+6
source

This is not how you use ls .

 array=(*) 
+6
source

any hint that you start:

 APACHE_CONF=/etc/apache2 SITES_TO_ENABLE="site1.org | site2.com" LIST_AVAILABLE=$(ls $APACHE_CONF/sites-available) LIST_ENABLED=$(ls $APACHE_CONF/sites-enabled) for site in $(echo $SITES_TO_ENABLE | sed -e "s/|//g") do FOUND=$(echo $LIST_AVAILABLE | sed -e "s/ /\n/g" | egrep $site) [[ ! -z $FOUND ]] && echo "Checking availability of $site: Ok" [[ -z $FOUND ]] && echo "Checking availability of $site: Nok, site \"$site\" required for production has not been found or is not defined" && exit 1 done 

You can combine this approach with course selection.

-1
source

Source: https://habr.com/ru/post/891897/


All Articles