我编写了很少的代码来描述我的问题。
#!/bin/bash
function writeToFile(){
echo "$1" >> file.txt
}
function checkLetters(){
letters_array+=( $1 )
count=0
for letter in ${letters_array[*]}
do
if [[ "$1" == "$letter" ]]
then
count=$((count+1))
fi
done
value=1
if [[ $count -eq $value ]]
then
writeToFile "$1"
fi
echo "return"
}
letters=( a b c d e )
for i in {1..2}
do
for letter in ${letters[*]}
do
checkLetters $letter
done
done
file="/mnt/file.txt"
while IFS= read -r line
do
printf "$line\n"
done <"$file"
`> file.txt`
因此,如果文件中还没有相同的字母,则代码会将字母写入文件。如果代码正常工作,则文件中必须包含字母a,b,c,d,e,并且如果我使用上述代码也是如此。 但是我需要从函数返回值,所以我要更改
checkLetters $letter
对此:
return_value=$(checkLetters $letter)
现在我的文件包含a,b,c,d,e,a,b ... 为什么? 为什么返回值会导致这种情况,以及如何使其正常工作?
答案 0 :(得分:1)
由于该命令(在本例中为功能ReadModel/Module/assigment/domain/assigmentRM.php
ReadModel/Module/assigment/domain/FileRM.php
ReadModel/Module/assigment/domain/AssignmentRepositoryInterface.php
ReadModel/Module/assigment/domain/FileRepositoryInterface.php
final class AssignmentRM
{
private $id;
private $title;
private $description;
private $videoLink;
private $files;
private $createdAt;
private $updatedAt;
private function __construct(
string $id,
string $title,
string $description,
string $videoLink,
string $files,
string $createdAt,
string $updatedAt
) {
$this->id = $id;
$this->title = $title;
$this->description = $description;
$this->videoLink = $videoLink;
$this->files = $files;
$this->createdAt = $createdAt;
$this->updatedAt = $updatedAt;
}
}
final class FileRM
{
private $id;
private $fileName;
private $studentId;
private $studentName;
private $assigmentId;
private $createdAt;
private $updateAt;
}
final class AssignmentRepositoryInterface
{
findById();
}
final class FileRepositoryInterface
{
findByFileId();
findByStudentId();
}
)在子Shell中执行,该子Shell继承了现有的checkLetters
但仅更新其本地副本。
形成bash(1)手册页:
Bash通过在子shell环境中执行命令并将命令替换替换为命令的标准输出来执行扩展,并删除所有尾随的换行符。嵌入的换行符不会被删除,但是可以在分词时将其删除。命令替换$(cat文件)可以替换为等效但更快的$(<文件)。
因此,如果您使用,将会发生完全相同的事情
letters_array
示例:
( checkLetters $letter; )
导致:
arr=( )
function test() {
arr+=( $1 )
echo "in test ($1): ${arr[*]}"
}
test 1; test 2;
echo ${arr[*]}
echo "substitution: $(test 3)"
echo "After command substitution: ${arr[*]}"
( test 5; echo "in subshell: ${arr[*]}"; )
echo "after subshell: ${arr[*]}"