5

I have two files. file1 is executable and file2 is just a text file and I use them frequently but I have to do cd every time to reach the directory.

How can I make file1 universally executable in terminal and how to access the content of file2 irrespective of my location in terminal. Is it possible to add content of file2 in man page so that I can just do man file2.

I think this can be done using /etc/environment but I want to know proper method of doing this.

2
  • you don't have to cd, you can just type the full path from anywhere, for example less ~/mystuff/file2 and that can be made into an alias, or you can add mystuff to your path, etc, etc, as explained in linked post
    – Zanna
    Dec 3, 2016 at 7:32
  • @Zanna Thanks for the link. Trying those solutions.
    – Rahul
    Dec 3, 2016 at 7:36

3 Answers 3

3

PATH environment variable is for this purpose. Add directories contain file1 and file2 to PATH, then you can access then by only the file name.

To add directory /opt/myapp to PATH environment variable use this:

PATH=/opt/myapp:"$PATH"

You can add above command to ~/.bashrc for permanent change. Run source .bashrc to reload .bashrc for current terminal.

Another way is to make a soft link of file1 and files to inside /usr/bin directory.

2

You have the solution how to run an executable without typing the full path already. So I will suggest a solution to the second problem.

I guess that you have one or only a few special files, that you want to access directly. I suggest that you view them with less (which is also used for man pages). I also guess that your files have names different from executable programs. Otherwise you should rename them in order to avoid confusion. (For example, it is a bad idea to access a file called sudo with this method.)

You can create an alias, and store that alias in your file ~/.bashrc

alias file2='less /path/to/file2'

where you replace /path/to/ with the actual directory path.

Run

file2

and check that it works. When it works you can add the alias command line into your ~/.bashrc file near the other aliases. Run

source ~/.bashrc

to get it active in already opened terminal windows. The next time you log in, it will be there for you to use.

2

I solved this using link provided by @Zanna.

For file1:

sudo ln -s /full/path/to/my/file1 /usr/local/bin/name_of_new_command

And for file2 I wrote a function in ~/.bashrc file as,

file2 () {
 pwd=$PWD
 cd /full/path/to/my/file2_directory
 if [ "$1" == "more" ] || [ "$1" == "less" ]; then
    $1 file2
    cd $pwd
 else
    $1 file2 &
    cd $pwd
 fi 
}

This way I can open file2 in less, more, gedit or any other editor by passing extra argument like:

file2 less
file2 more
file2 gedit
1
  • Yes, a function is a good tool, particularly if the task is more advanced. For simple tasks, an alias might be more convenient.
    – sudodus
    Dec 3, 2016 at 8:03

Not the answer you're looking for? Browse other questions tagged .