0

I created a script called mcd in bash that I can then use directly from the command line. But when I restart Linux, I can't use it. So the written script is not saved by default. Maybe there is a way to save custom scripts?

at first:

hanyuchi@TABLET-1DDNDEN4:~$ mcd () {
> mkdir -p "$1"
> cd "$1"
> }
hanyuchi@TABLET-1DDNDEN4:~$ mcd example2
hanyuchi@TABLET-1DDNDEN4:~/example2$ cd ..
hanyuchi@TABLET-1DDNDEN4:~$ tree
.
├── UTF-8
├── brightness
├── example
├── example2
├── last-modified.txt
├── one
│   └── a
└── two
    └── b

4 directories, 5 files

after restarting the system:

hanyuchi@TABLET-1DDNDEN4:~$ mcd example3
Command 'mcd' not found, but can be installed with:
sudo apt install mtools
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 1
    That's not a script, it's a function. You should learn what a script actually is, like do a tutorial. – wjandrea May 09 '23 at 18:19
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea May 09 '23 at 18:20
  • 1
    Although, if you made that into a script, [it wouldn't work](/q/255414/4518341). So a function is in fact the right choice and Manfred and Moishe's answers make sense. – wjandrea May 09 '23 at 18:27

2 Answers2

2

Your function is only defined within the current shell. It's not even available in another shell next to the first one; you don't have to restart the entire system to see this effect. If you want to provide it to every (new) shell, you need to define it in a file read by the shell during startup, usually ~/.bashrc for bash.

Manfred
  • 2,269
  • 1
  • 5
  • 14
1

What you have written is a function. Your problem here is that you have just written the function in the existing terminal, so when you close that terminal you lose the function. (The word "script" is typically used to refer to a file containing shell commands and/or functions, but you have not saved your function in a file.)

You need to save this function in a file that your terminal loads when it opens. Depending on how your system is set up, you may already have a file in your home directory named .bashrc, .bash_profile, or something similar. If you already have such a file, put your function into it. Than any time you open a new terminal, your function will be loaded and ready to use.

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116