官术网_书友最值得收藏!

  • Bash Cookbook
  • Ron Brash Ganesh Naik
  • 209字
  • 2021-07-23 19:17:32

Including/importing a library script and using external functions

To prepare for this example, create the following two files and open both:

  • io_maker.sh
  • library.sh

Inside library.sh, add the following:

#!/bin/bash

function create_file() {
local FNAME=$1
touch "${FNAME}"
ls "${FNAME}" # If output doesn't return a value - file is missing
}

function delete_file() {
local FNAME=$1
rm "${FNAME}"
ls "${FNAME}" # If output doesn't return a value - file is missing
}

Inside io_maker.sh, add the following:

#!/bin/bash

source library.sh # You may need to include the path as it is relative
FNAME="my_test_file.txt"
create_file "${FNAME}"
delete_file "${FNAME}"

exit 0

When you run the script, you should get the same output:

$ bash io_maker.sh
my_test_file.txt
ls: cannot access 'my_test_file.txt': No such file or directory

Although not obvious, we can see that both functions are executed. The first line of output is the ls command, successfully finding my_test_file.txt after creating the file in create_file(). In the second line, we can see that ls returns an error when we delete the file passed in as a parameter. 

Unfortunately, up until now, we have only been able to create and call functions, and execute commands. The next step, discussed in the next section, is to retrieve commands and function return codes or strings.

主站蜘蛛池模板: 共和县| 松原市| 桂林市| 茶陵县| 福建省| 晋城| 文昌市| 西乌珠穆沁旗| 额济纳旗| 那坡县| 襄城县| 山西省| 德庆县| 米泉市| 福建省| 麻城市| 宁远县| 孝昌县| 揭阳市| 威海市| 岳池县| 开江县| 寿光市| 安徽省| 湖州市| 铁岭县| 阿克苏市| 丹东市| 汝南县| 济阳县| 镶黄旗| 焉耆| 盱眙县| 宁蒗| 东乌| 尼玛县| 浦江县| 汉源县| 五家渠市| 胶州市| 陕西省|