在ubuntu中的.bashrc文件中调用隐藏的shell脚本文件

时间:2014-03-20 07:02:14

标签: linux bash shell sh

我已经创建了一个shell脚本并放在了主目录中。但是为了让它看不见,我把DOT放在它的名字前面。我的意思是.filename.sh。现在我想通过.bashrc文件调用此文件,该文件也是不可见的并放在主目录中。

我试过

sh .filename.shsh filename.sh但都没有成功。

# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

. filename.sh   #I'm trying to call this script here at the beginning of the file

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

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
...
...  #some more content in .bashrc file
...

每当我们在终端打开新选项卡或窗口时,这个shell脚本都会在终端上打印一些内容。

编辑: 我试过. .filename.sh,但只有当我们在主目录中时我才有意义(user@user$) 但它应该适用于所有目录,我的意思是无论我在哪里(例如假设我在桌面user@user:~/Desktop$中),现在如果我打开一个新选项卡它会显示错误。它应该工作,因为当我将相同的内容直接放在.bashrc文件而不是调用这个sh文件时,它适用于所有目录。

2 个答案:

答案 0 :(得分:3)

如果要获取文件,可以使用两种不同的符号。你可以写

source path/to/filename

但你也可以写

. path/to/filename

来自manual

  

&#34 ;. filename [arguments] ...这个内置函数等同于source。"

也许在你的情况下,你会被点符号弄糊涂。通过在文件前加上一个点作为前缀,您可以将其设为隐藏文件。这意味着您需要的是文件名前面的第二个点,或者只使用source命令,在我看来这是更好的符号,更难以错过。 :) 另外,为了安全起见,您应该包含路径并使用引号,以防您的文件名中包含必须正常转义的字符。

因此,考虑到您的文件存在于主目录的根目录中,以下应该这样做。我添加了一个测试来检查它的存在:

import="~/.filename.sh"

if [[ -f "$import" ]]; then
    source "$import"
else
    echo "Could not source ${import}. File does not exist."
fi

答案 1 :(得分:1)

如果.bashrc和脚本在同一目录中,请尝试使用以下内容

. ./.filename.sh

如果脚本存在于主目录

中,请使用此选项
. ~/.filename.sh