Bash wildcard in a makefile not working - bash

I have this makefile:
SHELL := /bin/bash -f
working :
if [ -d ffprob_runfail ]; then echo "gotcha" ;fi
error :
if [ -d ffprob_* ]; then echo "gotcha" ;fi
Executing 'make working' in a folder where the subdirectory 'ffprob_runfail' exists echoes:
if [ -d ffprob_runfail ]; then echo "gotcha" ;fi
gotcha
Executing 'make error' in the same folder echoes:
if [ -d ffprob_* ]; then echo "gotcha" ;fi
I am not sure where this 'surprising' behavior comes from - either miscoding in make or bash syntax. I tried escaping * but did not work. Might be an issue with the syntax of [ ] bash operator? (I am quite new to bash, after 20 years of csh pain...)
Any hint appreciated.
POST EDIT:
Not only the -f option disables globbing (thanks #choroba), but also the -d operator in bash is unary, and cannot used safely with globbing, i.e. refer to Bash Shell Script: confirm the existance of one or more directories.
So this looks to be the right way (continuation of the previous makefile...):
right :
for item in ffprob_* ; do if [ -d "$$item" ] ; \
then echo "gotcha $$item";fi;done

The -f option for bash means the same as the -f option to set, namely
-f Disable file name generation (globbing).
With globbing disabled, wildcards aren't expanded.
So, why do you set the shell to bash -f? Remove the -f.

Related

How to remove a single command from bash autocomplete

How do I remove a single "command" from Bash's auto complete command suggestions? I'm asking about the very first argument, the command, in auto complete, not asking "How to disable bash autocomplete for the arguments of a specific command"
For example, if I have the command ls and the system path also finds ls_not_the_one_I_want_ever, and I type ls and then press tab, I want a way to have removed ls_not_the_one_I_want_ever from every being a viable option.
I think this might be related to the compgen -c list, as this seems to be the list of commands available.
Background: WSL on Windows is putting all the .dll files on my path, in addition to the .exe files that should be there, and so I have many dlls I would like to remove in my bash environment, but I'm unsure how to proceed.
Bash 5.0's complete command added a new -I option for this.
According to man bash —
complete -pr [-DEI] [name ...]
[...] The -I option indicates that other supplied options and actions should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as ; or |, which is usually command name completion. [...]
Example:
function _comp_commands()
{
local cur=$2
if [[ $cur == ls* ]]; then
COMPREPLY=( $(compgen -c "$cur" | grep -v ls_not_wanted) )
fi
}
complete -o bashdefault -I -F _comp_commands
Using #pynexj's answer, I came up with the following example that seems to work well enough:
if [ "${BASH_VERSINFO[0]}" -ge "5" ]; then
function _custom_initial_word_complete()
{
if [ "${2-}" != "" ]; then
if [ "${2::2}" == "ls" ]; then
COMPREPLY=($(compgen -c "${2}" | \grep -v ls_not_the_one_I_want_ever))
else
COMPREPLY=($(compgen -c "${2}"))
fi
fi
}
complete -I -F _custom_initial_word_complete
fi

how to check if a file exist and is a text file?

Hi everyone I need to check if a file exist with a shell script. I did some digging and ended up with this syntax but I'm not sure why it isn't working
(please bear in mind that you are talking to beginner)
I've found that you can add -e for example to check if it exist but I didn't get where these shortcuts came form or their names
#! /bin/bash
if [ "$#" = "1" ]
then
if [ -e $($1) ] && [ -f $($1) ]
then echo 'the file exists'
fi
fi
In idiomatic Bash:
#!/usr/bin/env bash
if [[ -f "${1-}" ]]
then
echo 'the file exists'
fi
Correct shebang
[[ rather than [
-f implies -e
No need for semicolons or single-use variables.
Please keep in mind that this does not tell you whether the file is a text file. The only "definition" of a text file as opposed to any other file is whether it contains only printable characters, and even that falls short of dealing with UTF BOM characters and non-ASCII character sets. For that you may want to look at the non-authoritative output of file "${1-}", for example:
$ file ~/.bashrc
/home/username/.bashrc: ASCII text
More in the Bash Guide.
#!/bin/bash
if [ "$#" == 1 ]; then
if [[ -e "$1" && -f "$1" ]]; then
echo 'The file exists';
fi
fi
You should put every conditional && between [[ ]] symbols otherwise it will be interpreted as execute if success.
#! /bin/sh
FILE=$1 # get filename from commandline
if [ -f $FILE ]; then
echo "file $FILE exists"
fi
See the fine manual page of test commands, which are built-in in the different shells: man test; man sh; man bash
You will also find many shell primers which explain this very nicely.
Or see bash reference manual: https://www.gnu.org/software/bash/manual/bash.pdf

Bash script takes wrong conditional path for unknown reason [duplicate]

This question already has answers here:
Bash if [ -d $1] returning true for empty $1
(3 answers)
Closed 5 years ago.
I have the following bash script that should list the folders in the same directory, and let me choose a folder to move in, and then list its content.
#!/bin/bash
PS3="Scelta?"
select dest in $( command ls -aF | grep "/" ); do
if [ -d $dest ]; then
cd $dest
echo "$0 : changed to $dest"
ls
break
else
echo "$0 : wrong choice" 1>$2
fi
done
the path of the script is something like
/Users/myName/Documents/GitHub/SO/Exercise4
and this is the content of the Exercise4 dir
1/ 2/ 3/ 4/ 5/ select.sh
when I run the script it prompts me something like
1) ./
2) ../
3) 1/
4) 2/
5) 3/
6) 4/
7) 5/
Scelta? 
If I choose an option between 1 and 7 the script works, but when I input a number out of that range, instead of echoing me "wrong choice" it lists me my home directory and I can't figure out why
Why This Happens
Consider:
dest=
[ -d $dest ]
What does this do? It runs the command:
[ -d ]
What does that do? It's shorthand for:
[ -n "-d" ]
...which is to say, it checks whether -d is empty, which it isn't, so the result is true.
How To Stop It
Use More Quotes
Consider this instead:
dest=""
[ -d "$dest" ]
When run, it doesn't invoke [ -d ]; instead, it runs [ -d '' ]: The quotes prevented the expansion results from being split into a different number of strings than they started as.
When On Bash, Consider The Extended Test Form
[[ -d $dest ]]
...suppresses string-splitting and glob expansion, so it works even without quotes.
It's possible it has something to do with the fact that you're using Classic Test
[ vs [[
if [[ -d $dest ]]; then
http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression#behaviour_differences_compared_to_the_builtin_test_command
Or, you might just have to put quotations around it to evaluate correctly. It might just be that 8 is true and only 0 is false:
if [ -d "$dest" ]; then
I find the latter more likely; I make it a policy to quote absolutely everything all the time in bash, it's good practice.

Make fails checking if directory exists

I googled for this, but I can't figure out why Bash complains with the following code to check if a directory exists:
test.mk
#!/bin/bash
MYDIR="dl"
all:
if [ ! -d $MYDIR ]; then
#if [ ! -d "${MYDIR}" ]; then
#if [ ! -d ${MYDIR} ]; then
#Here
fi
make -f test.mk
if [ ! -d YDIR ]; then
/bin/sh: Syntax error: end of file unexpected
make: *** [all] Error 2
Does someone know why it fails? And why does it call /bin/sh instead of /bin/bash? Thank you.
Edit: unlike Bash, make doesn't support multi-line block. Here's working code:
MYDIR="dl"
all:
if [ ! -d ${MYDIR} ]; then\
echo "Here";\
else\
echo "There";\
fi
The #!/bin/bash shebang that you inserted at top is useless, and it is treated by make as a comment.
make sends by default commands to /bin/sh. To specify a different shell, use the macro SHELL = /bin/bash.
Moreover, you need to escape your variable:
if [ ! -d ${MYDIR} ]
I'm not sure if make can handle multi-line statements, so try to put all the if block in a line.
if [ ! -d ${MYDIR} ]; then DO_SOMETHING; DO_SOMETHING_ELSE; fi
You're feeding test.mk to make, not to bash. Then make sends individual lines to the shell, not whole blocks.
make uses its SHELL macro to determine which shell to use. You can override it to make it use bash.
The reason why you're getting YDIR is that make has silly rules about variable interpolation. Write $(MYDIR), not $MYDIR.
try bracing your variable:
${MYDIR}

bash if -a vs -e option

Both about -a and -e options in Bash documentation is said:
-a file
True if file exists.
-e file
True if file exists.
Trying to get what the difference is I ran the following script:
resin_dir=/Test/Resin_wheleph/Results
if [ -e ${resin_dir} ] ; then
echo "-e ";
fi
if [ ! -e ${resin_dir} ] ; then
echo "! -e";
fi
if [ -a ${resin_dir} ] ; then
echo "-a";
fi
if [ ! -a ${resin_dir} ] ; then
echo "! -a";
fi
/Test/Resin_wheleph/Results exists and is a directory. And this is what I get:
-e
-a
! -a
which seems to be a little strange (notice -a and ! -a). But when I use double brackets (e. g. if [[ -e ${resin_dir} ]]) in the similar script it gives reasonable output:
-e
-a
So:
What is a difference between -a and -e options?
Why -a produces a strange result when used inside single brackets?
I researched, and this is quite hairy:
-a is deprecated, thus isn't listed in the manpage for /usr/bin/test anymore, but still in the one for bash. Use -e . For single '[', the bash builtin behaves the same as the test bash builtin, which behaves the same as /usr/bin/[ and /usr/bin/test (the one is a symlink to the other). Note the effect of -a depends on its position: If it's at the start, it means file exists. If it's in the middle of two expressions, it means logical and.
[ ! -a /path ] && echo exists doesn't work, as the bash manual points out that -a is considered a binary operator there, and so the above isn't parsed as a negate -a .. but as a if '!' and '/path' is true (non-empty). Thus, your script always outputs "-a" (which actually tests for files), and "! -a" which actually is a binary and here.
For [[, -a isn't used as a binary and anymore (&& is used there), so its unique purpose is to check for a file there (although being deprecated). So, negation actually does what you expect.
The '-a' option to the test operator has one meaning as a unary operator and another as a binary operator. As a binary operator, it is the 'and' connective (and '-o' is the 'or' connective). As a unary operator, it apparently tests for a file's existence.
The autoconf system advises you to avoid using '-a' because it causes confusion; now I see why. Indeed, in portable shell programming, it is best to combine the conditions with '&&' or '||'.
I think #litb is on the right track. When you have '! -a ${resin_dir}', Bash may be interpreting it as "is the string '!' non-empty and is the string in '${resin_dir}' non-empty, to which the answer is yes. The Korn shell has a different view on this, and the Bourne shell yet another view - so stay away from '-a'.
On Solaris 10:
$ bash -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
Bad
$ ksh -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
OK
$ sh -c 'x=""; if [ ! -a "$x" ] ; then echo OK ; else echo Bad; fi'
sh: test: argument expected
$
The double bracket [[ exp ]] is a bash builtin. In bash -a and -e are the same, probably for some backwards compatibility.
The single bracket [ exp ] is an alias for the external command "test". In "test", -a is a logical AND. Although [ nothing AND $STRING ] looks like it should be false, test has some syntax quirks, which is why I recommend using the bash builtin [[ exp ]], which tends to be more sane.
Note:
bash really does call /bin/[ when you use "[".
$ [ $UNASIGNED_VAR == "bar" ]
bash: [: ==: unary operator expected
the error shows bash called [. An strace also shows "execve("/usr/bin/[", ..."

Resources