简体   繁体   中英

Can't detect whether a shell function is defined from a script

I have a bash script that is supposed to check if the user has a function defined, then if there is not function that exists, will define the function in their ~/.bashrc file. I've simplified the code for display purposes. Here is the script:

#!/bin/bash

brc="$HOME/.bashrc"

exists=false

# check if the function exists
if [ -n "$(type -t cs)" ] && [ "$(type -t cs)" = function ]; then 
    exists=true 
fi

if [ "$exists" = false ]; then
    echo "true"
else
    echo "false"
fi

Through a lot of echo tests, I've figured out that regardless of whether the function called cs exists for me, the first conditional statement always evaluates to false . The strange thing is that, when I copy and paste those lines into my shell directly without running a script, the line evaluates to true ! Please help.

Unless they've been exported with export -f , functions are local to a single instance of the shell . Your script runs in a different instance.

If you want your command to be able to determine which shell functions are active, you should either write it to be sourced into an existing shell rather than executed as an external command, or define it as a shell function itself.

You could also source in .bashrc , if you're willing to deal with your script's behavior being modified by its side effects:

brc="$HOME/.bashrc"
[[ -e "$brc" ]] && source "$brc"

By default .bashrc will not be loaded for non-interactive shells, for example this is from my (default) .bashrc :

# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

Or you might have something like:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

So you need to either figure out how to load the .bashrc in a non-interactive shell (depends on the way it's checked in your system) or source the function from another file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM