简体   繁体   中英

Shell functions - non active after command call

In ~/bin I have a shell script called foo , and in this script, I have the following, and only the following:

#!/bin/bash
func(){
   echo this is func
}

Now whenever I'm logged on, if I call foo , I expect the entire shell script to be ran. That is, after typing foo on the command line, there then exists a shell function called func that simply echos "this is func". However, this is not the case. Even if I call foo , func still doesn't exist.

How do I make that function exist? Indeed, I could make an alias in ~/.bashrc , but let's assume we're only restrained to shell scripts within bin.

EDIT: foo is marked executable. I am able to call foo without any problems; that is, if I type foo , then I receive no standard error, so I know foo was implemented. However, the function func within foo appears not to be.

If you run a script as a command, it runs in a subprocess, and any changes it makes to the environment have no effect on the original shell process. If you want it to modify the original shell process, you need to source it.

source ~/bin/foo

or

. ~/bin/foo

If ~/bin is in your $PATH you can simplify this to

. foo

Is ~/bin in your PATH? Also is ~/bin/foo marked executable? If not, chmod +X ~/bin/foo .

Edit:

Proper syntax should be as follows

#!/bin/bash
func() {
  echo This is func
}

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